问:
How to customize a URL at which a specific HTML file will load?
I have 3 separate HTML files:

index.html for a Home page

about.html for an About Us page

contact.html for a Contact Us page

At the moment, when I go to the URL .../ or .../index.html, the browser displays the index.html file, for .../html/about.html it shows the about.html file, etc.

However, I would like to make it so that the index.html file content will be shown when I type in the URL .../home, the about.html when I go to .../about-us, etc.

Also, to each of these 3 pages, I am adding links to the other two pages, so when someone is on the Home page, for example, and clicks on the About Us link from there, I would like them to be redirected to the URL .../about-us where the about.html file content will be shown (the content is showing correctly even now, but the redirect is to .../html/about.html instead of .../about-us).

How can I achieve this please (using any of the following: HTML/CSS/JS/Node.js)? I have seen this done for a SPA using React (react-router-dom), but without React I am not sure how to do it. Thank you!

Project file structure

Link elements from index.html:

```<code><header>
        <a href="index.html">Home</a>
        <a href="/html/contact.html">Contact Us</a>
        <a href="/html/about.html">About Us</a>
</header>
</code>```

I was not able to figure out how to achieve it using JS code to modify the window.location.href in the .js files linked to the HTML files, so I tried to set up a server with Node.js to add the routes needed, but that does not feel like the right approach. And, it did not solve the issue with redirecting to the desired URL in the browser when clicking the links.

Body:
I have 3 separate HTML files:

index.html for a Home page

about.html for an About Us page

contact.html for a Contact Us page

At the moment, when I go to the URL .../ or .../index.html, the browser displays the index.html file, for .../html/about.html it shows the about.html file, etc.

However, I would like to make it so that the index.html file content will be shown when I type in the URL .../home, the about.html when I go to .../about-us, etc.

Also, to each of these 3 pages, I am adding links to the other two pages, so when someone is on the Home page, for example, and clicks on the About Us link from there, I would like them to be redirected to the URL .../about-us where the about.html file content will be shown (the content is showing correctly even now, but the redirect is to .../html/about.html instead of .../about-us).

How can I achieve this please (using any of the following: HTML/CSS/JS/Node.js)? I have seen this done for a SPA using React (react-router-dom), but without React I am not sure how to do it. Thank you!

Project file structure

Link elements from index.html:

        Home
        Contact Us
        About Us

I was not able to figure out how to achieve it using JS code to modify the window.location.href in the .js files linked to the HTML files, so I tried to set up a server with Node.js to add the routes needed, but that does not feel like the right approach. And, it did not solve the issue with redirecting to the desired URL in the browser when clicking the links.


来源: stackexchange

问:
How to make a dual y-axis line plot with a polynomial function in ggplot2?
I need help with the modification of a plot with y-axis. In Excel I don't have trouble, but the hard part is in R. Besides, I uploaded an example of the final plot in excel.
It is not relevant the data you used.

I will appreciate your help.

Required double y-axis with polynomial function plot:

```<code>#Make lm model
Model<- lm(V~ T,data=data1)
summary(Model)
anova(Model)
HSD.test(Model, 'T', group = T, MSerror, alpha = 0.05, console = T)

#Make eq

eq <- function(data1){
  m<- lm(V~T);
  eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2,
                   list(a = format(unname(coef(m)[1]), digits = 2),
                        b = format(unname(coef(m)[2]), digits = 2),
                        r2 = format(summary(m)$r.squared, digits = 3)))
}

#Make plot
ggplot(data, aes(x=Time, y=mean))+
  geom_line()+
  geom_smooth(method=loess)+
  stat_regline_equation(label.y = 4.0e-06, aes(label=..eq.label..))+
  stat_regline_equation(label.y = 3.8e-06, aes(label=..rr.label..))+
  geom_pointrange(aes(ymin=mean-se, ymax=mean+se))+
  theme(
    line = element_line(colour = "black", size = 1, linetype = 1, lineend = "butt"),
    rect = element_rect(fill = "white", colour = "black", size = 1, linetype = 1),
    aspect.ratio = 1,
    plot.background = element_rect(fill = "white"),
    plot.margin = margin(1, 1, 1, 1, "cm"),

    axis.text = element_text(size = rel(2.5), colour = "#000000", margin = 1),
    strip.text = element_text(size = rel(0.8)),
    axis.line = element_blank(),
    axis.text.x = element_text(vjust = 0.2, angle=0),
    axis.text.y = element_text(hjust = 1),
    axis.ticks = element_line(colour = "#000000", size = 1.2),
    axis.title.x = element_text(size = 30, vjust=0.5),
    axis.title.y = element_text(size = 30, angle = 90),
    axis.ticks.length = unit(0.1, "cm"),

    legend.background = element_rect(colour = NA),
    legend.margin = unit(0.15, "cm"),
    legend.key = element_rect(fill = "grey95", colour = "white"),
    legend.key.size = unit(1.2, "lines"),
    legend.key.height = NULL,
    legend.key.width = NULL,
    legend.text = element_text(size = rel(2.0)),
    legend.text.align = NULL,
    legend.title = element_text(size = rel(2.0), face = "bold", hjust = 0),
    legend.title.align = NULL,
    legend.position = "right",
    legend.direction = NULL,
    legend.justification = "right",
    legend.box = NULL,

    panel.background = element_rect(fill = "#ffffff", colour = "#000000",
                                    size = 2, linetype = "solid"),

    panel.border = element_rect(colour = "black", fill=NA, size=2),

  )+
  ylab(expression(Volume~(m^3))) + xlab(expression(Time~(min)))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need help with the modification of a plot with y-axis. In Excel I don't have trouble, but the hard part is in R. Besides, I uploaded an example of the final plot in excel.
It is not relevant the data you used.

I will appreciate your help.

Required double y-axis with polynomial function plot:

#Make lm model
Model<- lm(V~ T,data=data1)
summary(Model)
anova(Model)
HSD.test(Model, 'T', group = T, MSerror, alpha = 0.05, console = T)

#Make eq

eq <- function(data1){
  m<- lm(V~T);
  eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2,
                   list(a = format(unname(coef(m)[1]), digits = 2),
                        b = format(unname(coef(m)[2]), digits = 2),
                        r2 = format(summary(m)$r.squared, digits = 3)))
}

#Make plot
ggplot(data, aes(x=Time, y=mean))+
  geom_line()+
  geom_smooth(method=loess)+
  stat_regline_equation(label.y = 4.0e-06, aes(label=..eq.label..))+
  stat_regline_equation(label.y = 3.8e-06, aes(label=..rr.label..))+
  geom_pointrange(aes(ymin=mean-se, ymax=mean+se))+
  theme(
    line = element_line(colour = "black", size = 1, linetype = 1, lineend = "butt"),
    rect = element_rect(fill = "white", colour = "black", size = 1, linetype = 1),
    aspect.ratio = 1,
    plot.background = element_rect(fill = "white"),
    plot.margin = margin(1, 1, 1, 1, "cm"),

    axis.text = element_text(size = rel(2.5), colour = "#000000", margin = 1),
    strip.text = element_text(size = rel(0.8)),
    axis.line = element_blank(),
    axis.text.x = element_text(vjust = 0.2, angle=0),
    axis.text.y = element_text(hjust = 1),
    axis.ticks = element_line(colour = "#000000", size = 1.2),
    axis.title.x = element_text(size = 30, vjust=0.5),
    axis.title.y = element_text(size = 30, angle = 90),
    axis.ticks.length = unit(0.1, "cm"),

    legend.background = element_rect(colour = NA),
    legend.margin = unit(0.15, "cm"),
    legend.key = element_rect(fill = "grey95", colour = "white"),
    legend.key.size = unit(1.2, "lines"),
    legend.key.height = NULL,
    legend.key.width = NULL,
    legend.text = element_text(size = rel(2.0)),
    legend.text.align = NULL,
    legend.title = element_text(size = rel(2.0), face = "bold", hjust = 0),
    legend.title.align = NULL,
    legend.position = "right",
    legend.direction = NULL,
    legend.justification = "right",
    legend.box = NULL,

    panel.background = element_rect(fill = "#ffffff", colour = "#000000",
                                    size = 2, linetype = "solid"),

    panel.border = element_rect(colour = "black", fill=NA, size=2),

  )+
  ylab(expression(Volume~(m^3))) + xlab(expression(Time~(min)))


问:
disable and enable drop down items in tkinter Python
I am trying to make a UI interface that can disable options from other menus besides the working menu, but then switches enables the options when selecting a different option within the working menu, overriding previous disables in other menus.

For example, if I press '2' in First menu, then all other menus will disable '2'.
If I press '1' in the First menu, then all other menus will disable '1', but now 2 will be enabled.
If I press '2' in the second menu, then now all other menus will have '2' disabled besides the second menu, and all other menus will have '1' disabled besides the first menu.

I tried to make puedo code that tries to depict the logic, though it might not work:

```<code>- take in I clicked on '2' in First menu.
- check to see if my last click was for in the First menu, finds no previous click, and enable nothing across all menus First, Second, Third, Fourth, Fifth, and Sixth.
- try to disable '2' on menus Second, Third, Fourth, Fifth, and Sixth, if they have that option.

- take in I clicked on '1' in the First menu.
- check to see if my last click was for in the First menu, finds that I clicked '1' and enables '1' across all menus First, Second, Third, Fourth, Fifth, and Sixth.
- try to disable '1' on menus Second, Third, Fourth, Fifth, and Sixth, if they have that option.

- take in that I clicked on '4' in the Second menu.
- check to see if my last click was for in the first menu, finds no previous click, and enables nothing across all menus First, Second, Third, Fourth, Fifth, and Sixth.
- try to disable '4' on menus First, Third, Fourth, Fifth, and Sixth, if they have that option.
</code>```

Here is what I tried to do/already have below:

```<code>from tkinter import *
from tkinter import ttk, messagebox

# Create the Frame and menubar
root = Tk()
root.title('Example Run')
root.iconbitmap('') #None for now, specifying directory on computer
root.geometry("1000x500")

#Create Menu
menubar = Menu(root)
root.config(menu=menubar)

# Create the menu widgets
First = Menu(menubar, tearoff = False)
Second = Menu(menubar, tearoff = False)
Third = Menu(menubar, tearoff = False)
Fourth = Menu(menubar, tearoff = False)
Fifth = Menu(menubar, tearoff = False)
Sixth = Menu(menubar, tearoff = False)

Menu_Choices = [First, Second, Third, Fourth, Fifth, Sixth]

# Add menu widgets to the menubar
menubar.add_cascade(menu=First, label="First")
menubar.add_cascade(menu=Second, label="Second")
menubar.add_cascade(menu=Third, label="Third")
menubar.add_cascade(menu=Fourth, label="Fourth")
menubar.add_cascade(menu=Fifth, label="Fifth")
menubar.add_cascade(menu=Sixth, label="Sixth")

# Define the names of each menu
First_list = ['1','2','3','4','5']
Second_list = ['2','4','6','8','10']
Third_list = ['3','6','9','12','18']
Fourth_list = ['1','3','5','7','9']
Fifth_list = ['2','3','5','7','8']
Sixth_list = ['END']
menu_list_items = [First_list, Second_list, Third_list, Fourth_list, Fifth_list, Sixth_list]

def disable_menuitem(menu_item):
        enable_all_menus()
        for i, m in enumerate(menu_list_items):
            if menu_item in m:
                menus[i].entryconfig(m.index(menu_item)+1, state="disabled")

# Function to enable all of the menu items
def enable_all_menus():
    for i, m in enumerate(menu_list_items):
        for j in m:
            menus[i].entryconfig(m.index(j), state="normal")

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

Body:
I am trying to make a UI interface that can disable options from other menus besides the working menu, but then switches enables the options when selecting a different option within the working menu, overriding previous disables in other menus.

For example, if I press '2' in First menu, then all other menus will disable '2'.
If I press '1' in the First menu, then all other menus will disable '1', but now 2 will be enabled.
If I press '2' in the second menu, then now all other menus will have '2' disabled besides the second menu, and all other menus will have '1' disabled besides the first menu.

I tried to make puedo code that tries to depict the logic, though it might not work:

- take in I clicked on '2' in First menu.
- check to see if my last click was for in the First menu, finds no previous click, and enable nothing across all menus First, Second, Third, Fourth, Fifth, and Sixth.
- try to disable '2' on menus Second, Third, Fourth, Fifth, and Sixth, if they have that option.

- take in I clicked on '1' in the First menu.
- check to see if my last click was for in the First menu, finds that I clicked '1' and enables '1' across all menus First, Second, Third, Fourth, Fifth, and Sixth.
- try to disable '1' on menus Second, Third, Fourth, Fifth, and Sixth, if they have that option.

- take in that I clicked on '4' in the Second menu.
- check to see if my last click was for in the first menu, finds no previous click, and enables nothing across all menus First, Second, Third, Fourth, Fifth, and Sixth.
- try to disable '4' on menus First, Third, Fourth, Fifth, and Sixth, if they have that option.

Here is what I tried to do/already have below:

from tkinter import *
from tkinter import ttk, messagebox

# Create the Frame and menubar
root = Tk()
root.title('Example Run')
root.iconbitmap('') #None for now, specifying directory on computer
root.geometry("1000x500")

#Create Menu
menubar = Menu(root)
root.config(menu=menubar)

# Create the menu widgets
First = Menu(menubar, tearoff = False)
Second = Menu(menubar, tearoff = False)
Third = Menu(menubar, tearoff = False)
Fourth = Menu(menubar, tearoff = False)
Fifth = Menu(menubar, tearoff = False)
Sixth = Menu(menubar, tearoff = False)

Menu_Choices = [First, Second, Third, Fourth, Fifth, Sixth]

# Add menu widgets to the menubar
menubar.add_cascade(menu=First, label="First")
menubar.add_cascade(menu=Second, label="Second")
menubar.add_cascade(menu=Third, label="Third")
menubar.add_cascade(menu=Fourth, label="Fourth")
menubar.add_cascade(menu=Fifth, label="Fifth")
menubar.add_cascade(menu=Sixth, label="Sixth")

# Define the names of each menu
First_list = ['1','2','3','4','5']
Second_list = ['2','4','6','8','10']
Third_list = ['3','6','9','12','18']
Fourth_list = ['1','3','5','7','9']
Fifth_list = ['2','3','5','7','8']
Sixth_list = ['END']
menu_list_items = [First_list, Second_list, Third_list, Fourth_list, Fifth_list, Sixth_list]

def disable_menuitem(menu_item):
        enable_all_menus()
        for i, m in enumerate(menu_list_items):
            if menu_item in m:
                menus[i].entryconfig(m.index(menu_item)+1, state="disabled")

# Function to enable all of the menu items
def enable_all_menus():
    for i, m in enumerate(menu_list_items):
        for j in m:
            menus[i].entryconfig(m.index(j), state="normal")

root.mainloop()


问:
Imputing values for a categorical feature
I have a categorical feature that takes calues ‘yes’ or ‘no’ and it has 50% missing values how can i impute missing values for this feature is there ant specefic way of imputing values for features with such high number of nan’s ?</p>


问:
Limiting Hibernate Queries
Ok. Hopefully this isn't too broad.

I have an application that I inherited which uses hibernate to run queries. There is a query getting passed to the database server that doesn't have a where clause and therefore returning every record that exists. I tried to reproduce it for quite some time with no success. It's weird because the query continues to run for 6 hours on the database server but it's the application server that is getting its resources maxed out.

My question is, if there's a way on a global level to prevent the query itself from being executed in hibernate? Or other ways that this can get addressed?

Title: Limiting Hibernate Queries


问:
Is it possible to pass input values from command line to variables in Jest test? (Node.JS)
I hope to implement a function that would allow me to pass input values from the command line and then export those values into my Jest test.

Currently, I have a prompt function that prompts users for their inputs. However, the function will never run -- the test case will always run and neglect the function.


问:
JavaScript Cell with same values as others is represented as null
I looked up if similar questions were already asked did not get a good answer. I have cells that have that outer HTML

```<code><div class="cell cellSymbol" id="cell" data-x="2" data-y="8" style="width: calc((100% / 9) - 0.5 * var(--shadowsize)); height: calc((100% / 9) - 0.5 * var(--shadowsize));"></div>
</code>```

which is accessible and another like that

```<code><div class="cell" id="cell" data-x="3" data-y="8" style="width: calc((100% / 9) - 0.5 * var(--shadowsize)); height: calc((100% / 9) - 0.5 * var(--shadowsize));"></div>
</code>```

which´s values are not accessible. Since they are totally the same besides having different classes I do not understand why my query selector says the second one is null and the first one is not.

Uncaught (in promise) TypeError: cell is null

is the error message if I click the null cell.

Thanks for the help.

Body:
I looked up if similar questions were already asked did not get a good answer. I have cells that have that outer HTML

which is accessible and another like that

which´s values are not accessible. Since they are totally the same besides having different classes I do not understand why my query selector says the second one is null and the first one is not.

Uncaught (in promise) TypeError: cell is null

is the error message if I click the null cell.

Thanks for the help.


问:
How to add the possibility of multi curl requests to the general method of sending curl?
How to add the possibility of multi curl requests to the general method of sending cURL (curl_init | curl_multi_init), or rather rewrite it to multi curl, because when sending one url, it will work as usual.

Here is my existing method of sending cURL (it needs to be modified to multi curl)

```<code>// A common method for sending requests via curl

    private function request($type, $url, $data = [], $headers = [], $curlopts = [])
    {
        $default_headers = [
            'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Encoding:gzip, deflate, lzma',
            'Accept-Language:ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4',
            'Upgrade-Insecure-Requests:1',
            'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36 OPR/42.0.2393.517'
        ];

        $default_curlopts = [
            //CURLOPT_INTERFACE => '46.254.16.170',
            CURLOPT_URL => (strpos($url, 'https://') === 0 ? '' : 'https://site.ru') . $url . ($type == 'GET' && count($data) > 0 ? '?' . http_build_query($data) : ''),
            CURLOPT_HTTPHEADER => array_merge($default_headers, $headers),
            CURLOPT_FOLLOWLOCATION => false,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER => true,
            CURLOPT_ENCODING => 'gzip',
            CURLOPT_COOKIEFILE => $this->auth_cookie_file,
            CURLOPT_COOKIEJAR => $this->auth_cookie_file,
            CURLOPT_FOLLOWLOCATION => true
        ];

        if ($type == 'POST') {
            $default_curlopts[CURLOPT_POST] = true;
            $default_curlopts[CURLOPT_POSTFIELDS] = http_build_query($data);
        }

        curl_setopt_array($this->ch, array_replace($default_curlopts, $curlopts));

        sleep($this->sleep_time);
        $response = (string)curl_exec($this->ch);

        $result = [
            'http_code' => curl_getinfo($this->ch, CURLINFO_HTTP_CODE),
            'raw_response' => $response,
            'header_size' => curl_getinfo($this->ch, CURLINFO_HEADER_SIZE)
        ];

        $result['header'] = mb_substr($response, 0, $result['header_size'], 'UTF-8');
        $result['headers'] = array_filter(array_map('trim', explode("\n", $result['header'])));
        $result['body'] = mb_substr($response, $result['header_size'], null, 'UTF-8');

        return $result;
    }
</code>```

This is my multi curl

```<code>// Todas url gravadas em array
$urls = [
"https://site.ru",
"https://site2.ru"
];

// Setando opção padrão para todas url e adicionando a fila para processamento
$mh = curl_multi_init();

foreach($urls as $key => $url) {
$ch[$key] = curl_init();
curl_setopt($ch[$key], CURLOPT_URL, $url);
curl_setopt($ch[$key], CURLOPT_RETURNTRANSFER, TRUE);
curl_multi_add_handle($mh, $ch[$key]);
}

// Executando consulta
do {
  curl_multi_exec($mh, $running);
  curl_multi_select($mh);
} while ($running > 0);

// Obtendo dados de todas as consultas e retirando da fila
foreach(array_keys($ch) as $key){

                $content = curl_multi_getcontent($ch[$key]);

                $results[$key] = $content;

                curl_multi_remove_handle($mh, $ch[$key]);

}

// Finalizando
curl_multi_close($mh);

var_dump($content);
</code>```

I tried to refine the method myself, but I didn't figure it out.

Thanks!

Body:
How to add the possibility of multi curl requests to the general method of sending cURL (curl_init | curl_multi_init), or rather rewrite it to multi curl, because when sending one url, it will work as usual.

Here is my existing method of sending cURL (it needs to be modified to multi curl)

// A common method for sending requests via curl

    private function request($type, $url, $data = [], $headers = [], $curlopts = [])
    {
        $default_headers = [
            'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Encoding:gzip, deflate, lzma',
            'Accept-Language:ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4',
            'Upgrade-Insecure-Requests:1',
            'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36 OPR/42.0.2393.517'
        ];

        $default_curlopts = [
            //CURLOPT_INTERFACE => '46.254.16.170',
            CURLOPT_URL => (strpos($url, 'https://') === 0 ? '' : 'https://site.ru') . $url . ($type == 'GET' && count($data) > 0 ? '?' . http_build_query($data) : ''),
            CURLOPT_HTTPHEADER => array_merge($default_headers, $headers),
            CURLOPT_FOLLOWLOCATION => false,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER => true,
            CURLOPT_ENCODING => 'gzip',
            CURLOPT_COOKIEFILE => $this->auth_cookie_file,
            CURLOPT_COOKIEJAR => $this->auth_cookie_file,
            CURLOPT_FOLLOWLOCATION => true
        ];

        if ($type == 'POST') {
            $default_curlopts[CURLOPT_POST] = true;
            $default_curlopts[CURLOPT_POSTFIELDS] = http_build_query($data);
        }

        curl_setopt_array($this->ch, array_replace($default_curlopts, $curlopts));

        sleep($this->sleep_time);
        $response = (string)curl_exec($this->ch);

        $result = [
            'http_code' => curl_getinfo($this->ch, CURLINFO_HTTP_CODE),
            'raw_response' => $response,
            'header_size' => curl_getinfo($this->ch, CURLINFO_HEADER_SIZE)
        ];

        $result['header'] = mb_substr($response, 0, $result['header_size'], 'UTF-8');
        $result['headers'] = array_filter(array_map('trim', explode("\n", $result['header'])));
        $result['body'] = mb_substr($response, $result['header_size'], null, 'UTF-8');

        return $result;
    }

This is my multi curl

// Todas url gravadas em array
$urls = [
"https://site.ru",
"https://site2.ru"
];

// Setando opção padrão para todas url e adicionando a fila para processamento
$mh = curl_multi_init();

foreach($urls as $key => $url) {
$ch[$key] = curl_init();
curl_setopt($ch[$key], CURLOPT_URL, $url);
curl_setopt($ch[$key], CURLOPT_RETURNTRANSFER, TRUE);
curl_multi_add_handle($mh, $ch[$key]);
}

// Executando consulta
do {
  curl_multi_exec($mh, $running);
  curl_multi_select($mh);
} while ($running > 0);

// Obtendo dados de todas as consultas e retirando da fila
foreach(array_keys($ch) as $key){

                $content = curl_multi_getcontent($ch[$key]);

                $results[$key] = $content;

                curl_multi_remove_handle($mh, $ch[$key]);

}

// Finalizando
curl_multi_close($mh);

var_dump($content);

I tried to refine the method myself, but I didn't figure it out.

Thanks!


问:
PyInstaller add root certificate to executable
I have created a Python application and am packaging it with PyInstaller. On my own computer, I have configured my own trust store CA bundle to include my company's proxy based on Self-Signed Certificate Authorities pip / conda but I don't understand how to bring that into the PyInstaller executable so it works on other people's computers who have not configured their own trust store CA bundle.

The error I get is [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain

I am using PyInstaller 5.7.0 (with --onefile option), certifi 2022.12.7, and Python 3.8. This is primarily a dash application (2.7.1). First, the user selects a ZIPcode and I use uszipcode (version 0.2.6) to get information on that ZIPcode. That is where the error first occurs.

The application runs correctly when disconnected from the VPN. When I generate the executable, I use the --add-data flag to include cacert.pem from the certifi Python package. I tried manually adding my company's cert to the cacert.pem but it will get overwritten if I update certifi.

Where should I add in my company's SSL certificate so users don't have to disconnect from the VPN to use the application?


问:
How to put an item on DynamoDB table using AWS SDK for Node.js?
I have a DynamoDB table named MYTABLE. I'm trying to insert some data into this table via LambdaEdge.

My Lambda function is triggered via a CloudFront Distribution.

I have this function:

```<code>    var AWS = require("aws-sdk");
    AWS.config.update({region: 'us-east-1'});
    var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'});

    exports.handler = async (event, context) => {
        var params = {
            TableName: 'MYTABLE',
            Item: {
              'id' : {'S': 'something'},
              'value' : {'S': 'something'}
            }
        };

          // Call DynamoDB to add the item to the table
        await ddb.putItem(params, function(err, data) {
            if (err) {
              console.log("Error", err);
            } else {
              console.log("Success", data);
            }
        });

        const response = {
            status: '302',
            statusDescription: 'Found',
            headers: {
                location: [{
                    key: 'Location',
                    value: 'https://www.google.com',
                }],
            },
        };
        return response;
    };
</code>```

The function runs properly (the redirection works) but no data is inserted into the table.

What am I doing wrong?

Body:
I have a DynamoDB table named MYTABLE. I'm trying to insert some data into this table via LambdaEdge.

My Lambda function is triggered via a CloudFront Distribution.

I have this function:

    var AWS = require("aws-sdk");
    AWS.config.update({region: 'us-east-1'});
    var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'});

    exports.handler = async (event, context) => {
        var params = {
            TableName: 'MYTABLE',
            Item: {
              'id' : {'S': 'something'},
              'value' : {'S': 'something'}
            }
        };

          // Call DynamoDB to add the item to the table
        await ddb.putItem(params, function(err, data) {
            if (err) {
              console.log("Error", err);
            } else {
              console.log("Success", data);
            }
        });

        const response = {
            status: '302',
            statusDescription: 'Found',
            headers: {
                location: [{
                    key: 'Location',
                    value: 'https://www.google.com',
                }],
            },
        };
        return response;
    };

The function runs properly (the redirection works) but no data is inserted into the table.

What am I doing wrong?


问:
WatchOS - How to avoid device sleeping during downloads
I'm using URLSession to download a .zip file when the first view appears, and it works fine.

The problem is that if the user's device sleeps after a duration (I believe 15/75 seconds are the options in settings) or by tilting their wrist etc - the download fails and the user has to retry when they open the app back up.

Other than warning the user to interact with the device during download, or changing their settings (neither ideal), is there anything I can do? It's not a huge file, around 10mb but poor networks could take a while.


问:
How to use JsonSerializable on function in Flutter
I want to improve the functioning of my application a bit using json_serializable. I use the https://www.thecocktaildb.com/api.php Here is the code for the model that is currently in the app.
`

```<code>class CocktailModel {
  final String name;
  final String category;
  final String alcoholic;
  final String glassType;
  final String pictureUrl;
  final String instructions;
  final List<IngredientModel> ingredientsList;

  CocktailModel({
    required this.name,
    required this.category,
    required this.alcoholic,
    required this.glassType,
    required this.pictureUrl,
    required this.instructions,
    required this.ingredientsList,
  });

  CocktailModel.fromJson(Map<String, dynamic> json)
      : name = json['strDrink'] ?? '',
        category = json['strCategory'] ?? '',
        alcoholic = json['strAlcoholic'] ?? '',
        glassType = json['strGlass'] ?? '',
        pictureUrl = json['strDrinkThumb'] ?? '',
        instructions = json['strInstructions'] ?? '',
        ingredientsList = _getIngredients(json);

  static List<IngredientModel> _getIngredients(
    Map<String, dynamic> json,
  ) {
    List<IngredientModel> ingredientsList = [];

    for (var i = 1; i <= 16; i++) {
      if (json['strIngredient$i'] == null) {
        continue;
      }
      if (json['strMeasure$i'] == null) {
        continue;
      }
      ingredientsList.add(
        IngredientModel(
          name: json['strIngredient$i'],
          mesure: json['strMeasure$i'],
        ),
      );
    }
    return ingredientsList;
  }
}
</code>```

Unfortunately, in one case I don't know how to use it correctly because I have a certain function (_getIngredients) created that adds more ingredients and measures to me in the right way.
How do I need to write this _getIngredients function so that json_serializable generates the right g.dart file??

I tried to do this in this way, but unfortunately I get null from the api:

```<code>import 'package:random_cocktail_app/domain/models/ingredient_model.dart';
import 'package:json_annotation/json_annotation.dart';

part 'cocktail_model.g.dart';

@JsonSerializable()
class CocktailModel {
  @JsonKey(name: 'strDrink')
  final String name;

  @JsonKey(name: 'strCategory')
  final String category;

  @JsonKey(name: 'strAlcoholic')
  final String alcoholic;

  @JsonKey(name: 'strGlass')
  final String glassType;

  @JsonKey(name: 'strDrinkThumb')
  final String pictureUrl;

  @JsonKey(name: 'strInstructions')
  final String instructions;

  **@JsonKey(fromJson: _getIngredients)
  final List<IngredientModel> ingredientsList;**

  CocktailModel({
    required this.name,
    required this.category,
    required this.alcoholic,
    required this.glassType,
    required this.pictureUrl,
    required this.instructions,
    required this.ingredientsList,
  });

  factory CocktailModel.fromJson(Map<String, dynamic> json) =>
      _$CocktailModelFromJson(json);

  Map<String, dynamic> toJson() => _$CocktailModelToJson(this);

  **static List<IngredientModel> _getIngredients(
    Map<String, dynamic> json,
  ) {
    List<IngredientModel> ingredientsList = [];

    for (var i = 1; i <= 16; i++) {
      if (json['strIngredient$i'] == null) {
        continue;
      }
      if (json['strMeasure$i'] == null) {
        continue;
      }
      ingredientsList.add(
        IngredientModel(
          name: json['strIngredient$i'],
          mesure: json['strMeasure$i'],
        ),
      );
    }
    return ingredientsList;
  }**
}
</code>```

Thank you in advance if anyone can help me solve my problem :)

Body:
I want to improve the functioning of my application a bit using json_serializable. I use the https://www.thecocktaildb.com/api.php Here is the code for the model that is currently in the app.
`

class CocktailModel {
  final String name;
  final String category;
  final String alcoholic;
  final String glassType;
  final String pictureUrl;
  final String instructions;
  final List<IngredientModel> ingredientsList;

  CocktailModel({
    required this.name,
    required this.category,
    required this.alcoholic,
    required this.glassType,
    required this.pictureUrl,
    required this.instructions,
    required this.ingredientsList,
  });

  CocktailModel.fromJson(Map<String, dynamic> json)
      : name = json['strDrink'] ?? '',
        category = json['strCategory'] ?? '',
        alcoholic = json['strAlcoholic'] ?? '',
        glassType = json['strGlass'] ?? '',
        pictureUrl = json['strDrinkThumb'] ?? '',
        instructions = json['strInstructions'] ?? '',
        ingredientsList = _getIngredients(json);

  static List<IngredientModel> _getIngredients(
    Map<String, dynamic> json,
  ) {
    List<IngredientModel> ingredientsList = [];

    for (var i = 1; i <= 16; i++) {
      if (json['strIngredient$i'] == null) {
        continue;
      }
      if (json['strMeasure$i'] == null) {
        continue;
      }
      ingredientsList.add(
        IngredientModel(
          name: json['strIngredient$i'],
          mesure: json['strMeasure$i'],
        ),
      );
    }
    return ingredientsList;
  }
}

Unfortunately, in one case I don't know how to use it correctly because I have a certain function (_getIngredients) created that adds more ingredients and measures to me in the right way.
How do I need to write this _getIngredients function so that json_serializable generates the right g.dart file??

I tried to do this in this way, but unfortunately I get null from the api:

import 'package:random_cocktail_app/domain/models/ingredient_model.dart';
import 'package:json_annotation/json_annotation.dart';

part 'cocktail_model.g.dart';

@JsonSerializable()
class CocktailModel {
  @JsonKey(name: 'strDrink')
  final String name;

  @JsonKey(name: 'strCategory')
  final String category;

  @JsonKey(name: 'strAlcoholic')
  final String alcoholic;

  @JsonKey(name: 'strGlass')
  final String glassType;

  @JsonKey(name: 'strDrinkThumb')
  final String pictureUrl;

  @JsonKey(name: 'strInstructions')
  final String instructions;

  **@JsonKey(fromJson: _getIngredients)
  final List<IngredientModel> ingredientsList;**

  CocktailModel({
    required this.name,
    required this.category,
    required this.alcoholic,
    required this.glassType,
    required this.pictureUrl,
    required this.instructions,
    required this.ingredientsList,
  });

  factory CocktailModel.fromJson(Map<String, dynamic> json) =>
      _$CocktailModelFromJson(json);

  Map<String, dynamic> toJson() => _$CocktailModelToJson(this);

  **static List<IngredientModel> _getIngredients(
    Map<String, dynamic> json,
  ) {
    List<IngredientModel> ingredientsList = [];

    for (var i = 1; i <= 16; i++) {
      if (json['strIngredient$i'] == null) {
        continue;
      }
      if (json['strMeasure$i'] == null) {
        continue;
      }
      ingredientsList.add(
        IngredientModel(
          name: json['strIngredient$i'],
          mesure: json['strMeasure$i'],
        ),
      );
    }
    return ingredientsList;
  }**
}

Thank you in advance if anyone can help me solve my problem :)


问:
Why can't I use blob.text() in my React Native Expo app?
I am trying to use the blob.text() function in my React Native Expo app (example Expo snack demonstrating the issue here). When I call this function on a blob, I get the following error: Unhandled promise rejection Error: "testBlob.text is not a function. (In 'testBlob.text()', 'testBlob.text' is undefined)" in _callee$ << tryCatch <<  << asyncGeneratorStep

Creating a blob in this way then calling the text() function works just fine when running the code in the Chrome dev console- not sure why this is only happening in my Expo app.

Any clue why this is and/or what I need to do to be able to use the text() function on a blob?

Tried: Creating a new Blob object from a string with the linked blob constructor then calling the text() function to get the string back.
Expected behavior: Calling blob.text() should return the string that the blob was created from.
What actually resulted: The text() function is not recognized.


问:
Swift AttributedString font size resized by .76666 (recurring) when saved to RTF via NSAttributedString
iOS 16.2. XCode 14.2.

Block below is a simple AttributedString creation and save.

The two AttributedExtensions functions for custom append() and Bold().

The text is saved as an RTF file using NSAttributedString.

I have removed error checking.

```<code>var atr = AttributedString()

atr.append("Text 18\n", fontSize: 18)
atr.append(AttributedString.Bold("Bold Text 24", fontSize: 24)!)

if let rtfURL = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("file.rtf") {
    let nsa = NSAttributedString(atr)
    let data = try! nsa.data(from: NSRange(location: 0, length: nsa.length), documentAttributes: [NSAttributedString.DocumentAttributeKey.documentType : NSAttributedString.DocumentType.rtf])
    try data.write(to: url, options: Data.WritingOptions.atomic)
}
</code>```
```<code>extension AttributedString {
    mutating func append(_ s: String, fontName: String = "Helvetica", fontSize: CGFloat = 12, colour: UnvColour = .black) {
#if os(macOS)
        guard let font = NSFontManager.shared.font(withFamily: fontName, size: fontSize) else { return }
#else
        guard let font = UIFont(name: fontName, size: fontSize) else { return }
#endif
        let cont = AttributeContainer([NSAttributedString.Key.font : font, NSAttributedString.Key.foregroundColor : colour] )
        self.append(AttributedString(s, attributes: cont))
    }

static func Bold(_ s: String, colour: UnvColour = .black, fontName: String = "Helvetica", fontSize: CGFloat = 12) -> AttributedString? {
        if s.isEmpty { return AttributedString(s) }
#if os(macOS)
        guard let bold = NSFontManager.shared.font(withFamily: fontName, traits: .boldFontMask, weight: 5, size: fontSize) else { return nil }
#else

        guard let bold = UIFont(name: fontName, size: fontSize) else { return nil }
#endif
        let boldCont = AttributeContainer([NSAttributedString.Key.font : bold, NSAttributedString.Key.foregroundColor : colour] )
        var ab = AttributedString(s)
        ab.setAttributes(boldCont)
        return ab
    }
}
</code>```

When the file is saved and opened with TextEdit, the font sizes are scaled by .76666666666 (recurring). Size 18pt is now 13.8pt and 24pt is now 18.4pt.

The debugger shows the font sizes are 24 and 18 before the save.

This occurs on iPad device and iPhone simulator.

Anyone seen this before?

Body:
iOS 16.2. XCode 14.2.

Block below is a simple AttributedString creation and save.

The two AttributedExtensions functions for custom append() and Bold().

The text is saved as an RTF file using NSAttributedString.

I have removed error checking.

var atr = AttributedString()

atr.append("Text 18\n", fontSize: 18)
atr.append(AttributedString.Bold("Bold Text 24", fontSize: 24)!)

if let rtfURL = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("file.rtf") {
    let nsa = NSAttributedString(atr)
    let data = try! nsa.data(from: NSRange(location: 0, length: nsa.length), documentAttributes: [NSAttributedString.DocumentAttributeKey.documentType : NSAttributedString.DocumentType.rtf])
    try data.write(to: url, options: Data.WritingOptions.atomic)
}

extension AttributedString {
    mutating func append(_ s: String, fontName: String = "Helvetica", fontSize: CGFloat = 12, colour: UnvColour = .black) {
#if os(macOS)
        guard let font = NSFontManager.shared.font(withFamily: fontName, size: fontSize) else { return }
#else
        guard let font = UIFont(name: fontName, size: fontSize) else { return }
#endif
        let cont = AttributeContainer([NSAttributedString.Key.font : font, NSAttributedString.Key.foregroundColor : colour] )
        self.append(AttributedString(s, attributes: cont))
    }

static func Bold(_ s: String, colour: UnvColour = .black, fontName: String = "Helvetica", fontSize: CGFloat = 12) -> AttributedString? {
        if s.isEmpty { return AttributedString(s) }
#if os(macOS)
        guard let bold = NSFontManager.shared.font(withFamily: fontName, traits: .boldFontMask, weight: 5, size: fontSize) else { return nil }
#else

        guard let bold = UIFont(name: fontName, size: fontSize) else { return nil }
#endif
        let boldCont = AttributeContainer([NSAttributedString.Key.font : bold, NSAttributedString.Key.foregroundColor : colour] )
        var ab = AttributedString(s)
        ab.setAttributes(boldCont)
        return ab
    }
}

When the file is saved and opened with TextEdit, the font sizes are scaled by .76666666666 (recurring). Size 18pt is now 13.8pt and 24pt is now 18.4pt.

The debugger shows the font sizes are 24 and 18 before the save.

This occurs on iPad device and iPhone simulator.

Anyone seen this before?


问:
NextJS dynamic metatag without getServerSideProps
i want when u share a link from a topic in my forum it shows the title as the topic title, just like https://facebook.com/
that shows Facebook - log in or sign up

but i cant use
getServerSideProps
because i'm using html files to host (i need to) next build && next export -o

and its not supported on static html export:
https://nextjs.org/docs/advanced-features/static-html-export#unsupported-features

there is any other way to make it work?

i tried:

```<code>
import React from "react";
import { useQuery } from "react-query";
import { fetchTopic } from "../../fetchers/forum";
import EmptyChangingPage from "../empty";
import Head from "next/head";
import { useRouter } from "next/router";
import { baseURL } from "../../baseUrl";

export default function Topic() {
  const router = useRouter();
  const { topicId } = router.query;
  //
  const {
    data: topic,
    isLoading: isLoadingTopic,
    isFetched: isFetchedTopic,
  } = useQuery([`topic:${topicId}`], () => fetchTopic(Number(topicId)), {
    staleTime: 60000,
    enabled: topicId !== undefined,
  });
  if (isLoadingTopic || !isFetchedTopic)
    return <EmptyChangingPage />;
  return (
    <>
      <Head>
        <meta property="og:type" content="website" />
        <meta
          property="og:image"
          content={`http://${baseURL}/imgs/og_logo.png`}
        />
        <meta
          property="og:url"
          content={`http:/${baseURL}/forum/topic/?topicId=${topic?.topicId}`}
        />
        <meta property="og:title" content={`Forum - ${topic?.title}`} />
        <meta
          property="og:description"
          content={`content - ${topic?.message}`}
        />
      </Head>
      <main>
        <div style={{ backgroundColor: "#dcdcdc" }}>
          {/* forum stuff */}
        </div>
      </main>
    </>
  );
}
</code>```

but when i send a link it shows
Forum - undefined
content - undefined

Body:
i want when u share a link from a topic in my forum it shows the title as the topic title, just like https://facebook.com/
that shows Facebook - log in or sign up

but i cant use
getServerSideProps
because i'm using html files to host (i need to) next build && next export -o

and its not supported on static html export:
https://nextjs.org/docs/advanced-features/static-html-export#unsupported-features

there is any other way to make it work?

i tried:

import React from "react";
import { useQuery } from "react-query";
import { fetchTopic } from "../../fetchers/forum";
import EmptyChangingPage from "../empty";
import Head from "next/head";
import { useRouter } from "next/router";
import { baseURL } from "../../baseUrl";

export default function Topic() {
  const router = useRouter();
  const { topicId } = router.query;
  //
  const {
    data: topic,
    isLoading: isLoadingTopic,
    isFetched: isFetchedTopic,
  } = useQuery([`topic:${topicId}`], () => fetchTopic(Number(topicId)), {
    staleTime: 60000,
    enabled: topicId !== undefined,
  });
  if (isLoadingTopic || !isFetchedTopic)
    return <EmptyChangingPage />;
  return (
    <>

        <meta property="og:type" content="website" />
        <meta
          property="og:image"
          content={`http://${baseURL}/imgs/og_logo.png`}
        />
        <meta
          property="og:url"
          content={`http:/${baseURL}/forum/topic/?topicId=${topic?.topicId}`}
        />
        <meta property="og:title" content={`Forum - ${topic?.title}`} />
        <meta
          property="og:description"
          content={`content - ${topic?.message}`}
        />

          {/* forum stuff */}

    </>
  );
}

but when i send a link it shows
Forum - undefined
content - undefined


问:
How to set fix size of RectangleSelector after erelease callback done on Python matplotlib?
I have multiple ax plot with partial code of RectangleSelector as below.

```<code>from matplotlib.widgets import RectangleSelector
import numpy as np
import matplotlib.pyplot as plt
from functools import partial

def select_callback(eclick, erelease, dataSize):
    x1, y1 = eclick.xdata, eclick.ydata
    x2, y2 = erelease.xdata, erelease.ydata
    //** I would like to set fix size of selection here  **//
    // ext = (0,dataSize,eclick.ydata,erelease.ydata)
    // May be I need selected.draw_shape(ext)

fig = plt.figure(constrained_layout=True)
axs = fig.subplots(4)

x = np.linspace(0, 10, 1000)

selectors = []
for idx,ax in enumerate(axs):
    ax.plot(x, np.sin(2*np.pi*x))  # plot something
    selectors.append(RectangleSelector(
        ax, partial(select_callback, dataSize=10),
        useblit=True,
        button=[1, 3],
        minspanx=5, minspany=5,
        spancoords='pixels',
        interactive=True))

plt.show()
</code>```

I would like to set fix size of selection with coordinate set e.g. x1, x2, y1, y2 after erelease callback done. Any advice or guidance on this would be greatly appreciated, Thanks.

Body:
I have multiple ax plot with partial code of RectangleSelector as below.

from matplotlib.widgets import RectangleSelector
import numpy as np
import matplotlib.pyplot as plt
from functools import partial

def select_callback(eclick, erelease, dataSize):
    x1, y1 = eclick.xdata, eclick.ydata
    x2, y2 = erelease.xdata, erelease.ydata
    //** I would like to set fix size of selection here  **//
    // ext = (0,dataSize,eclick.ydata,erelease.ydata)
    // May be I need selected.draw_shape(ext)

fig = plt.figure(constrained_layout=True)
axs = fig.subplots(4)

x = np.linspace(0, 10, 1000)

selectors = []
for idx,ax in enumerate(axs):
    ax.plot(x, np.sin(2*np.pi*x))  # plot something
    selectors.append(RectangleSelector(
        ax, partial(select_callback, dataSize=10),
        useblit=True,
        button=[1, 3],
        minspanx=5, minspany=5,
        spancoords='pixels',
        interactive=True))

plt.show()

I would like to set fix size of selection with coordinate set e.g. x1, x2, y1, y2 after erelease callback done. Any advice or guidance on this would be greatly appreciated, Thanks.


问:
How to resolve unable to find valid certification path to requested target, when trying to access prestodb table from pyspark?
trying to access the prestodb table from using pyspark with following code

```<code>spark = SparkSession.builder.master("local[*]").appName("testing presto connection").config('spark.driver.extraClassPath', 'dependencies/presto-jdbc-0.221.jar').getOrCreate()

jdbc_df = spark.read.jdbc(url="jdbc:presto://host:port/catalog_name",table="schema_name.table_name",
properties={"user": "username", "password": "password","SSL":"true"})
jdbc_df.show(10)
</code>```

But I'm getting error as below,

```<code>Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
</code>```

How to resolve that error?

Body:
trying to access the prestodb table from using pyspark with following code

spark = SparkSession.builder.master("local[*]").appName("testing presto connection").config('spark.driver.extraClassPath', 'dependencies/presto-jdbc-0.221.jar').getOrCreate()

jdbc_df = spark.read.jdbc(url="jdbc:presto://host:port/catalog_name",table="schema_name.table_name",
properties={"user": "username", "password": "password","SSL":"true"})
jdbc_df.show(10)

But I'm getting error as below,

Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

How to resolve that error?


问:
Issue with accessing value for textfield using form
```<code><html>
    <head>
        <title>Calculator</title>
        <script>
            var a = parseInt(document.form1.first.value);
            var b = parseInt(document.form1.second.value);
            var c;
            function Addition()
            {
                c=a+b;
                document.getElementById("pid").innerHTML="Addition of Two Numbers Entered is: "+c;
            }
            function Substraction()
            {
                c=a-b;
                document.getElementById("pid").innerHTML="Substraction of Two Numbers Entered is: "+c;
            }
            function Multiplication()
            {
                c=a*b;
                document.getElementById("pid").innerHTML="Multiplication of Two Numbers Entered is: "+c;
            }
            function Division()
            {
                c=a/b;
                document.getElementById("pid").innerHTML="Division of Two Numbers Entered is: "+c;
            }
        </script>
    </head>
    <body>
        <form name="form1">
            Enter First Number <input type="text" name="first"><br><br>
            Enter Second Number<input type="text" name="second"><br><br>
            <input type="button" value="Addition" onclick="Addition()">
            <input type="button" value="Substraction" onclick="Substraction()">
            <input type="button" value="Multiplication" onclick="Multiplication()">
            <input type="button" value="Division" onclick="Division()">
        </form>
        <p id="pid">Hello</p>
    </body>
</html>
</code>```

It is only showing undefined when i tried to access the value of a and b. I tried multiple time but its not working. It is not accessing the value and I want to do it with form only.

Body:
        <title>Calculator</title>

        <form name="form1">
            Enter First Number <input type="text" name="first">

            Enter Second Number<input type="text" name="second">

            <input type="button" value="Addition" onclick="Addition()">
            <input type="button" value="Substraction" onclick="Substraction()">
            <input type="button" value="Multiplication" onclick="Multiplication()">
            <input type="button" value="Division" onclick="Division()">
        </form>

Hello

It is only showing undefined when i tried to access the value of a and b. I tried multiple time but its not working. It is not accessing the value and I want to do it with form only.


问:
Remove parent entity without its child
I have 3 entities

```<code>
public class Movie {

    @OneToMany(cascade = CascadeType.REMOVE)
    private Set<RoleCharacter> characters = new HashSet<>();
}
</code>```
```<code>public class Person {

    @OneToMany()
    private Set<RoleCharacter> moviesStarred = new HashSet<>();

}
</code>```
```<code>public class RoleCharacter {

    @ManyToOne(cascade = {CascadeType.REFRESH, CascadeType.PERSIST})
    private Person actor;

    @ManyToOne
    private Movie movie;
}
</code>```

I am trying to delete a Movie firstly, then RoleCharacter and don't remove a Person.
Was able to remove first 2 of them, but now, I don't know how to persist the Person without removing it.

Title: Remove parent entity without its child

Body:
I have 3 entities

public class Movie {

    @OneToMany(cascade = CascadeType.REMOVE)
    private Set<RoleCharacter> characters = new HashSet<>();
}

public class Person {

    @OneToMany()
    private Set<RoleCharacter> moviesStarred = new HashSet<>();

}

public class RoleCharacter {

    @ManyToOne(cascade = {CascadeType.REFRESH, CascadeType.PERSIST})
    private Person actor;

    @ManyToOne
    private Movie movie;
}

I am trying to delete a Movie firstly, then RoleCharacter and don't remove a Person.
Was able to remove first 2 of them, but now, I don't know how to persist the Person without removing it.


问:
Running R from Excel using specific old R packages
First time question asker.

I created an Excel/R tool that uses:

Excel VBA to create a CSV file with data for R,

Launch R using a Windows Shell,

Detects when R is finished running and then

Imports the results in a CSV file created by the R script.

Unfortunately, the R code does not work as programed with some package versions created after 3/1/2020, which creates problems for new users because they cannot just install the current package versions or users who want to use conflicting versions for other projects.

I have a solution for users who do not require newer versions of R for their other work; writing a script that installs all the packages and their dependents using the “versions” package.  However, I think this approach will constrain users who want to use newer versions of R.  **Is this a correct assumption? **

I thought the {checkpoint} package might offer a good solution.  I can get it to run in well in RStudio by creating a RStudio project (where I ran the {checkpoint} package to install the 3/1/2020 versions of my packages).  However, I have not found a way to run the R script from the Windows Shell.  The R script does not seem to be able to access the packages installed in the RStudio project using {checkpoint}.  Does anyone have ideas of how I can have Excel VBA launch the start of the R script in a way that it can assess the packages installed in the RStudio project by {checkpoint}? Perhaps there is a Windows Shell call for RStudio similar to the one I use now for R?

Here is the Windows Shell code I currently use for R in case it helps.  It works with the versions approach but not the {checkpoint} approach.

```<code>rExeCall = "C:\Program Files\R\R-3.6.2\bin\Rscript.exe"
rExeOptns = " --no-environ --no-init-file --no-restore --verbose  "
rscrpt=”Tool.R”
Shell (rExeCall & rExeOptns & rscrpt)
</code>```

Thank you in advance for your help!

I had hoped that my current R shell code would work when I used {checkpoint} to install the correct versions of the packages in an RStudio project.

I tried specifying the .libPaths to the file location for the RStudio projection (per Running R script from PHP in VSCode not recognizing R packages) without success.

Body:
First time question asker.

I created an Excel/R tool that uses:

Excel VBA to create a CSV file with data for R,

Launch R using a Windows Shell,

Detects when R is finished running and then

Imports the results in a CSV file created by the R script.

Unfortunately, the R code does not work as programed with some package versions created after 3/1/2020, which creates problems for new users because they cannot just install the current package versions or users who want to use conflicting versions for other projects.

I have a solution for users who do not require newer versions of R for their other work; writing a script that installs all the packages and their dependents using the “versions” package.  However, I think this approach will constrain users who want to use newer versions of R.  **Is this a correct assumption? **

I thought the {checkpoint} package might offer a good solution.  I can get it to run in well in RStudio by creating a RStudio project (where I ran the {checkpoint} package to install the 3/1/2020 versions of my packages).  However, I have not found a way to run the R script from the Windows Shell.  The R script does not seem to be able to access the packages installed in the RStudio project using {checkpoint}.  Does anyone have ideas of how I can have Excel VBA launch the start of the R script in a way that it can assess the packages installed in the RStudio project by {checkpoint}? Perhaps there is a Windows Shell call for RStudio similar to the one I use now for R?

Here is the Windows Shell code I currently use for R in case it helps.  It works with the versions approach but not the {checkpoint} approach.

rExeCall = "C:\Program Files\R\R-3.6.2\bin\Rscript.exe"
rExeOptns = " --no-environ --no-init-file --no-restore --verbose  "
rscrpt=”Tool.R”
Shell (rExeCall & rExeOptns & rscrpt)

Thank you in advance for your help!

I had hoped that my current R shell code would work when I used {checkpoint} to install the correct versions of the packages in an RStudio project.

I tried specifying the .libPaths to the file location for the RStudio projection (per Running R script from PHP in VSCode not recognizing R packages) without success.


问:
Fourier series animation effect using by python ArtistAnimation
I'm studying about Fourier Series with python.
I drew it with cosine and sine function.

My code is like this.

```<code>import numpy as np
import matplotlib.pyplot as plt
from sympy import *
x = Symbol('x')

fx=0
j=10

for i in range(1,j):
    fx=fx+(2)/(np.pi*i)*(1-cos(i*np.pi))*(sin(i*x))
    y_func=lambdify(x, fx, "numpy")
    x_val=np.linspace(-np.pi,np.pi,315)
    y_val=y_func(x_val)
    plt.plot(x_val,y_val)
plt.show()
</code>```

I could get the correct graph.

And I tried to make the graph into animaion effect like this gif file.

enter image description here

I wrote the code like below using by ArtistAnimation , but I couldn't get the animation.

How can i get the animation?

```<code>import numpy as np
import matplotlib.pyplot as plt
from sympy import *
from matplotlib.animation import ArtistAnimation
x = Symbol('x')

fx=0
j=10
img=[]
fig, ax=plt.subplots(constrained_layout=True)

for i in range(1,j):
    fx=fx+(2)/(np.pi*i)*(1-cos(i*np.pi))*(sin(i*x))

    y_func=lambdify(x, fx, "numpy")

    x_val=np.linspace(-np.pi,np.pi,315)
    y_val=y_func(x_val)

    fs=plt.plot(x_val,y_val)
    img.append([fs])

anim=ArtistAnimation(fig,img,interval=5)
anim.save("Fourier_Series01.gif",fps=24)
</code>```

I tried to make the code with ArtistAnimation

Thank you for your answer

Body:
I'm studying about Fourier Series with python.
I drew it with cosine and sine function.

My code is like this.

import numpy as np
import matplotlib.pyplot as plt
from sympy import *
x = Symbol('x')

fx=0
j=10

for i in range(1,j):
    fx=fx+(2)/(np.pi*i)*(1-cos(i*np.pi))*(sin(i*x))
    y_func=lambdify(x, fx, "numpy")
    x_val=np.linspace(-np.pi,np.pi,315)
    y_val=y_func(x_val)
    plt.plot(x_val,y_val)
plt.show()

I could get the correct graph.

And I tried to make the graph into animaion effect like this gif file.

enter image description here

I wrote the code like below using by ArtistAnimation , but I couldn't get the animation.

How can i get the animation?

import numpy as np
import matplotlib.pyplot as plt
from sympy import *
from matplotlib.animation import ArtistAnimation
x = Symbol('x')

fx=0
j=10
img=[]
fig, ax=plt.subplots(constrained_layout=True)

for i in range(1,j):
    fx=fx+(2)/(np.pi*i)*(1-cos(i*np.pi))*(sin(i*x))

    y_func=lambdify(x, fx, "numpy")

    x_val=np.linspace(-np.pi,np.pi,315)
    y_val=y_func(x_val)

    fs=plt.plot(x_val,y_val)
    img.append([fs])

anim=ArtistAnimation(fig,img,interval=5)
anim.save("Fourier_Series01.gif",fps=24)

I tried to make the code with ArtistAnimation

Thank you for your answer


问:
How do i setting next.config.js rewrites with dynamic routing?
I use rewrites() to solve CORS error and it works ,
But dynamic routing does not work because of rewrites() - source & destination
(I think dynamic routing does not work because of -> "/:path*" )

I expect no CORS error and Dynamic routing at Next.config.js

(or I can Seperate api at other folder and no rewrites , but when i call api it occur CORS error )


问:
Pointer-to-function or pointer-to-object. What is the meaning of clang warning?
Sorry for possible duplicates. Because I couldn't find the answer

So my question is. I am trying to get an address to the function

```<code>void func() {}

void* funcPtr = func;
</code>```

I am using C++ 17 at Visual Studio and clang giving me that warning

```<code>implicit conversion between pointer-to-function and pointer-to-object is a microsoft extension[clang-diagnostic-microsoft-cast]
</code>```

I want to use it, to check if two pointer to a function are actually pointing to the same function. For example:

```<code>const std::function<void()>& stdFunc1 = func;
const std::function<void()>& stdFunc2 = func;

void* funcAdr1 = *stdFunc1.target<void(*)()>();
void* funcAdr2 = *stdFunc2.target<void(*)()>();

bool test = funcAdr1 == funcAdr2;
</code>```

What clang trying me to tell. And what possible workaround can I do? For my project it is not really necessary. But I want to know it for future.

Body:
Sorry for possible duplicates. Because I couldn't find the answer

So my question is. I am trying to get an address to the function

void func() {}

void* funcPtr = func;

I am using C++ 17 at Visual Studio and clang giving me that warning

implicit conversion between pointer-to-function and pointer-to-object is a microsoft extension[clang-diagnostic-microsoft-cast]

I want to use it, to check if two pointer to a function are actually pointing to the same function. For example:

const std::function<void()>& stdFunc1 = func;
const std::function<void()>& stdFunc2 = func;

void* funcAdr1 = *stdFunc1.target<void(*)()>();
void* funcAdr2 = *stdFunc2.target<void(*)()>();

bool test = funcAdr1 == funcAdr2;

What clang trying me to tell. And what possible workaround can I do? For my project it is not really necessary. But I want to know it for future.


问:
How to create API in laravel in route file
I'm trying to create a route in the api.php file in laravel 6, I'm returning a simple array just for testing, but it always gives an error, in the web.php routes file it works normally, but in the api.php file it doesn't work

```<code>Object { message: "", exception: "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException", file: "/var/www/vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php", line: 179, trace: (21) […] }
exception: "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException"
file: "/var/www/vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php"
line: 179
message: ""
trace: Array(21) [ {…}, {…}, {…}, … ]
0: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Routing/Router.php", line: 635, function: "match", … }
1: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Routing/Router.php", line: 624, function: "findRoute", … }
2: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Routing/Router.php", line: 613, function: "dispatchToRoute", … }
3: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php", line: 170, function: "dispatch", … }
4: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", line: 130, function: "Illuminate\\Foundation\\Http\\{closure}", … }
5: Object { file: "/var/www/app/Http/Middleware/Cors.php", line: 18, function: "Illuminate\\Pipeline\\{closure}", … }
6: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", line: 171, function: "handle", … }
7: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php", line: 21, function: "Illuminate\\Pipeline\\{closure}", … }
8: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", line: 171, function: "handle", … }
9: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php", line: 21, function: "Illuminate\\Pipeline\\{closure}", … }
10: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", line: 171, function: "handle", … }
11: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php", line: 27, function: "Illuminate\\Pipeline\\{closure}", … }
12: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", line: 171, function: "handle", … }
13: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php", line: 63, function: "Illuminate\\Pipeline\\{closure}", … }
14: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", line: 171, function: "handle", … }
15: Object { file: "/var/www/vendor/fideloper/proxy/src/TrustProxies.php", line: 57, function: "Illuminate\\Pipeline\\{closure}", … }
16: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", line: 171, function: "handle", … }
17: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", line: 105, function: "Illuminate\\Pipeline\\{closure}", … }
18: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php", line: 145, function: "then", … }
19: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php", line: 110, function: "sendRequestThroughRouter", … }
20: Object
</code>```

Code Route:

```<code>Route::get('/api-teste',
    ['uses' => 'RegisterController@show']
);
</code>```

Code Controller:

```<code>public function show()
    {
        return response()->json([
            'nome' => 'paulo',
            'genero' => 'masculino',
        ]);
    }
</code>```

I already tried with route resource and also, clear the cache

```<code>sudo docker exec -it phpgold-app php artisan optimize'
</code>```

OBS: I'm using docker container, but it works perfectly in the web.php file

Body:
I'm trying to create a route in the api.php file in laravel 6, I'm returning a simple array just for testing, but it always gives an error, in the web.php routes file it works normally, but in the api.php file it doesn't work

Object { message: "", exception: "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException", file: "/var/www/vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php", line: 179, trace: (21) […] }
exception: "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException"
file: "/var/www/vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php"
line: 179
message: ""
trace: Array(21) [ {…}, {…}, {…}, … ]
0: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Routing/Router.php", line: 635, function: "match", … }
1: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Routing/Router.php", line: 624, function: "findRoute", … }
2: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Routing/Router.php", line: 613, function: "dispatchToRoute", … }
3: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php", line: 170, function: "dispatch", … }
4: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", line: 130, function: "Illuminate\\Foundation\\Http\\{closure}", … }
5: Object { file: "/var/www/app/Http/Middleware/Cors.php", line: 18, function: "Illuminate\\Pipeline\\{closure}", … }
6: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", line: 171, function: "handle", … }
7: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php", line: 21, function: "Illuminate\\Pipeline\\{closure}", … }
8: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", line: 171, function: "handle", … }
9: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php", line: 21, function: "Illuminate\\Pipeline\\{closure}", … }
10: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", line: 171, function: "handle", … }
11: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php", line: 27, function: "Illuminate\\Pipeline\\{closure}", … }
12: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", line: 171, function: "handle", … }
13: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php", line: 63, function: "Illuminate\\Pipeline\\{closure}", … }
14: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", line: 171, function: "handle", … }
15: Object { file: "/var/www/vendor/fideloper/proxy/src/TrustProxies.php", line: 57, function: "Illuminate\\Pipeline\\{closure}", … }
16: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", line: 171, function: "handle", … }
17: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", line: 105, function: "Illuminate\\Pipeline\\{closure}", … }
18: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php", line: 145, function: "then", … }
19: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php", line: 110, function: "sendRequestThroughRouter", … }
20: Object

Code Route:

Route::get('/api-teste',
    ['uses' => 'RegisterController@show']
);

Code Controller:

public function show()
    {
        return response()->json([
            'nome' => 'paulo',
            'genero' => 'masculino',
        ]);
    }

I already tried with route resource and also, clear the cache

sudo docker exec -it phpgold-app php artisan optimize'

OBS: I'm using docker container, but it works perfectly in the web.php file


问:
angular viewport looks different on different browsers
working on an angular project and the layout looks vastly different on my iPhone (using safari) than it does on my desktop, also using safari. I think it may have something to do with view port settings, but not sure what can be done to fix it. any ideas?

This is my viewport code:

<meta name="viewport" content="viewport-fit=cover, width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">

Here is what its supposed to look like:

Instead it looks like this:

The text is very tiny and hard to read. any suggestions?


问:
C# web service that can have a JS client upload a file to store the file on our IIS Server
I have been building a simple c# web service(asmx) for a specific project where the client is a Javascript client.

We now have a requirement that the client can take a photo from their device, such as a tablet that is running the JS web site client side, and that photo needs to be upload to the server via some sort of end point...

All the examples I have been able to find with c# samples is where the client is on a c# web site with a file upload object on it.. but I can't do that as its a JS client.

I assume its possible to have a JS client side app, call and end point in my c# web service and have it upload the file, but I have not been able to figure out how to do this... that is what does the c# end point look like.. We have the JS client side all done just need the web service to deal with the client uploading the image file now..

Thanks

Everything online that I have found is examples of JS to PHP or where the client was on a c# website with a file upload object/control on it..

I have a client side JS web site so struggling to figure out how to do this file upload to our c# web service.


问:
Is it possible to isolate disk storage with container?
With the combination of namespace and cgroup, we can isolate a sets of processes for certain types of resources such as CPU and memory. Then I'm curious is it also possible to isolate disk storage? If so what cgroups/namespace are used? (I'd imagine sth like mount namespace?)

I ask this because disk partition play crucial role in lots of stateful applications, which are way more technically challenging. Will appreciate if anyone can share info about how Kubernetes or Facebook Twine handle stateful apps with heavy I/O such as databases.


问:
d3js sankey transition after drag event
I'm trying to build an interactive d3.js sankey chart that allows the user to do two things:

Drag each node across the x,y axes

Click an 'Update' button that randomises the values of each link and updates the sankey chart accordingly

The current status of my code is as follows:

The user is able to drag each node without issue

If the user has not dragged any nodes, the 'Update' button works without issue

However, if the user tries to click the 'Update' button after dragging a node, then the nodes and links become detached as the sankey has seemingly forgotten where the nodes were previously

My question is, is it possible to force a sankey recalculation that takes into account the 'new' position of each dragged node? If so, how would that be done?

My current code is here: https://plnkr.co/edit/F03OYn8e457NZZbD?preview

Snippet of the update() function in question

```<code>function update() {
//randomise the link values
sankeyData.links.forEach(function (link) {
    link.value = Math.max(Math.ceil(Math.random() * 10), 1)
})

//rerun sankey
sankeyData = sankey(sankeyData)

//update node positions
d3.selectAll(".sankey-node")
    .transition()
    .duration(1000)
    .attr("x", function (d) {
        return d.x0;
    })
    .attr("y", function (d) {
        return d.y0;
    })
    .attr("height", function (d) {
        return d.y1 - d.y0;
    })

//this only updates the y0 and y1 coords of each link?
sankey.update(sankeyData)

//update link positions
d3.selectAll(".sankey-link")
    .transition()
    .duration(1000)
    .attr("d", d3.sankeyLinkHorizontal())
    .style("stroke-width", function (d) {
        return Math.max(1, d.width);
    })
</code>```

}

Title: d3js sankey transition after drag event

Body:
I'm trying to build an interactive d3.js sankey chart that allows the user to do two things:

Drag each node across the x,y axes

Click an 'Update' button that randomises the values of each link and updates the sankey chart accordingly

The current status of my code is as follows:

The user is able to drag each node without issue

If the user has not dragged any nodes, the 'Update' button works without issue

However, if the user tries to click the 'Update' button after dragging a node, then the nodes and links become detached as the sankey has seemingly forgotten where the nodes were previously

My question is, is it possible to force a sankey recalculation that takes into account the 'new' position of each dragged node? If so, how would that be done?

My current code is here: https://plnkr.co/edit/F03OYn8e457NZZbD?preview

Snippet of the update() function in question

function update() {
//randomise the link values
sankeyData.links.forEach(function (link) {
    link.value = Math.max(Math.ceil(Math.random() * 10), 1)
})

//rerun sankey
sankeyData = sankey(sankeyData)

//update node positions
d3.selectAll(".sankey-node")
    .transition()
    .duration(1000)
    .attr("x", function (d) {
        return d.x0;
    })
    .attr("y", function (d) {
        return d.y0;
    })
    .attr("height", function (d) {
        return d.y1 - d.y0;
    })

//this only updates the y0 and y1 coords of each link?
sankey.update(sankeyData)

//update link positions
d3.selectAll(".sankey-link")
    .transition()
    .duration(1000)
    .attr("d", d3.sankeyLinkHorizontal())
    .style("stroke-width", function (d) {
        return Math.max(1, d.width);
    })

}


问:
Is it possible to let 'make' utilize all the isolated cpus for its parallel build jobs?
My x64 machine is running CentOS 8 and has 20 cpus.

Out of 20 cpus, only 2 cpus (0 and 1) are available for normal use and the rest 18 cpus (2-19) are isolated.

When I try taskset -c 2-19 make -j 15 for example, only 1 cpu out of the 18 seems to be used.

It looks like the cpuset specified by taskset is not applied to child processes.

Is it possible to let make and all the child processes fully utilize the isolated cpus?


问:
error installing older mono version despite following tutorial
I need to install an older version of mono and followed the official tutorial where I added in /etc/apt/sources.list.d/mono-xamarin.list the following

```<code>deb http://download.mono-project.com/repo/ubuntu stable/snapshots/4.8.1 main
</code>```

Updating the repository works out well. But when I try to install it via

```<code>sudo apt install mono-complete

or

sudo apt install mono-devel
</code>```

I am not getting version 4.8.1 as specified but the newest version 6.8.

What am I doing wrong here and how do I force install the older version?

Body:
I need to install an older version of mono and followed the official tutorial where I added in /etc/apt/sources.list.d/mono-xamarin.list the following

deb http://download.mono-project.com/repo/ubuntu stable/snapshots/4.8.1 main

Updating the repository works out well. But when I try to install it via

sudo apt install mono-complete

or

sudo apt install mono-devel

I am not getting version 4.8.1 as specified but the newest version 6.8.

What am I doing wrong here and how do I force install the older version?


问:
how to animation text disappear and come out in reactjs or css
I tried to do similar text animation as this lottiefiles website.

My logics was set width and content in object once changed, the css transition will made it look like animation but how to opacity the content before run interval function?

```<code>const AnimationComponent = () => {
  const [ contents, setContents ] = [
  { id: 1, text: "Collate", width: "140px" },
  { id: 2, text: "Manage", width: "159px" },
  { id: 3, text: "Organise", width: "179px" },
];

  const [showText, setShowText] = useState<IAnimate>(animated[0]);

  useEffect(() => {
    const intervalText = setInterval(() => {
      setShowText((prev) => {
        const index = prev.id - 1;
        if (index === -1) return animated[0];

        switch (animated[index].text) {
          case "Collate":
            return animated[1];
          case "Manage":
            return animated[2];
          case "Organise":
            return animated[0];
          default:
            return animated[0];
        }
      });
    }, 3000);

    return () => {
            clearInterval(intervalText);
        }
  }, []);

 return (
    <Animation as="div">
      <AnimateItem
        style={{ width: showText.width }}
       >
          {showText.text}
         </AnimateItem>
       <span> your</span>
    </Animation>
  )
}
</code>```

Body:
I tried to do similar text animation as this lottiefiles website.

My logics was set width and content in object once changed, the css transition will made it look like animation but how to opacity the content before run interval function?

const AnimationComponent = () => {
  const [ contents, setContents ] = [
  { id: 1, text: "Collate", width: "140px" },
  { id: 2, text: "Manage", width: "159px" },
  { id: 3, text: "Organise", width: "179px" },
];

  const [showText, setShowText] = useState<IAnimate>(animated[0]);

  useEffect(() => {
    const intervalText = setInterval(() => {
      setShowText((prev) => {
        const index = prev.id - 1;
        if (index === -1) return animated[0];

        switch (animated[index].text) {
          case "Collate":
            return animated[1];
          case "Manage":
            return animated[2];
          case "Organise":
            return animated[0];
          default:
            return animated[0];
        }
      });
    }, 3000);

    return () => {
            clearInterval(intervalText);
        }
  }, []);

 return (
    <Animation as="div">
      <AnimateItem
        style={{ width: showText.width }}
       >
          {showText.text}
         </AnimateItem>
        your
    </Animation>
  )
}


问:
how to properly set up a database config file for sequelize? i keep getting "TypeError: Cannot read properties of undefined (reading 'max')"
basically, i am trying to make my app choose which database it's going to use. i'm having trouble, because i keep getting a "TypeError: Cannot read properties of undefined (reading 'max')". i've spent about three hours on this (very new to web stack stuff, so don't laugh at me please) and could really use some assistance. thanks in advance.

db.config.js.

it doesn't work with pool active either, so don't mind that.

```<code>require('dotenv').config();

module.exports = {
  dev: {
    HOST: "localhost",
    USER: "postgres",
    PASSWORD: "redacted",
    DB: "testtest",
    //dialect: "mysql"
    dialect: "postgres"
  }, // pool was here, removed it to make the whole thing smaller
  production:{
    // empty until i get actual production values from my hosting service
  }
}
</code>```

index.js

```<code>const env = process.env.NODE_ENV || 'dev';
const config = require("../config/db.config.js");

const Sequelize = require("sequelize");
const sequelize = new Sequelize(
  config.DB,
  config.USER,
  config.PASSWORD,
  {
    host: config.HOST,
    dialect: config.dialect,
    operatorsAliases: false,

    pool: {
      // omitted to make example smaller
    }
  }
);

const db = {};

db.Sequelize = Sequelize;
db.sequelize = sequelize;

// ...models relationships defined here

module.exports = db;
</code>```

to my understanding,

```<code>const env = process.env.NODE_ENV || 'dev';
</code>```

means that if a value isn't present within my .env file (it isn't), it will default to 'dev' settings, and connect to my local database.

```<code>const config = require("../config/db.config.js");
</code>```

this is here so the file can access those values.

i tried making an entirely separate file for environment configuration, but it gave me a sequelize error (that i can't pull up right now). this is what i had before:

```<code>const dbEngine = process.env.DB_ENVIRONMENT || 'dev';
const config = require('./db.config')[dbEngine];

module.exports = require('sequelize')(config);
</code>```

Body:
basically, i am trying to make my app choose which database it's going to use. i'm having trouble, because i keep getting a "TypeError: Cannot read properties of undefined (reading 'max')". i've spent about three hours on this (very new to web stack stuff, so don't laugh at me please) and could really use some assistance. thanks in advance.

db.config.js.

it doesn't work with pool active either, so don't mind that.

require('dotenv').config();

module.exports = {
  dev: {
    HOST: "localhost",
    USER: "postgres",
    PASSWORD: "redacted",
    DB: "testtest",
    //dialect: "mysql"
    dialect: "postgres"
  }, // pool was here, removed it to make the whole thing smaller
  production:{
    // empty until i get actual production values from my hosting service
  }
}

index.js

const env = process.env.NODE_ENV || 'dev';
const config = require("../config/db.config.js");

const Sequelize = require("sequelize");
const sequelize = new Sequelize(
  config.DB,
  config.USER,
  config.PASSWORD,
  {
    host: config.HOST,
    dialect: config.dialect,
    operatorsAliases: false,

    pool: {
      // omitted to make example smaller
    }
  }
);

const db = {};

db.Sequelize = Sequelize;
db.sequelize = sequelize;

// ...models relationships defined here

module.exports = db;

to my understanding,

const env = process.env.NODE_ENV || 'dev';

means that if a value isn't present within my .env file (it isn't), it will default to 'dev' settings, and connect to my local database.

const config = require("../config/db.config.js");

this is here so the file can access those values.

i tried making an entirely separate file for environment configuration, but it gave me a sequelize error (that i can't pull up right now). this is what i had before:

const dbEngine = process.env.DB_ENVIRONMENT || 'dev';
const config = require('./db.config')[dbEngine];

module.exports = require('sequelize')(config);


问:
EtherCAT CoE acyclic data transmission triggered by internal event implementation
I am totally new to EtherCAT. I have Microchip LAN9255 based EtherCAT slave device and TwinCAT3 software tool as EtherCAT master. Some configuration data are required to send from EtherCAT master (TwinCAT3 master) to LAN9255 EtherCAT slave. This configuration data needs to be sent only when it is changed (acyclically). Also, I have  Slave Stack Code (SSC) Tool to generate slave stack code. With this tool I import one xlsx based application descriptor file.

Application descriptor file
In this xlsx based application descriptor file I want to change the transmission type of GPIO_OUTPUT object to Event driven (If the TwinCAT3 EtherCAT master recognizes a change of state). What changes are required in this application descriptor file and EtherCAT slave firmware?


问:
RDS Postgres: Resource disappear after convert to MultiAZ-cluster from single instance
One of my Single instance which is currently working and connected with application, I convert SingleInstance to MultiAZ-Cluster. After that instance is completly disappear from my RDS Console and dashboard, like i doesn't have any instance. But my application is still working, and all crud operation working fine.

Could any one please tell, is it usual, should i wait?


问:
Vite how to prevent ,js filename change to other format
I have config something like this

import { defineConfig } from "vite";

export default defineConfig({
    build: {
        lib: {
            entry: "src/main.ts",
            name: "main",
            fileName: "main",
            formats: ["cjs"],
        },
        outDir: ".",
        rollupOptions: {
            external: ["obsidian"],
            output: {
                globals: {
                    obsidian: "obsidian",
                },
            },
        },
    },
});
```

After build command it creates main.cjs file, I want it to be just main.js.
How can I achieve this.

Body:
I have config something like this

import { defineConfig } from "vite";

export default defineConfig({
    build: {
        lib: {
            entry: "src/main.ts",
            name: "main",
            fileName: "main",
            formats: ["cjs"],
        },
        outDir: ".",
        rollupOptions: {
            external: ["obsidian"],
            output: {
                globals: {
                    obsidian: "obsidian",
                },
            },
        },
    },
});

After build command it creates main.cjs file, I want it to be just main.js.
How can I achieve this.


问:
How to get value from localstorage Chromedriver python
I am always getting None result when I read value "token" from discord verification link. How can I get token value from localstorage for Chromedriver?

import undetected_chromedriver as webdriver
import time

recreate_localStorage_script = '''
    const iframe = document.createElement('iframe');
    document.head.append(iframe);
    const pd = Object.getOwnPropertyDescriptor(iframe.contentWindow, 'localStorage');
    iframe.remove();
    Object.defineProperty(window, 'localStorage', pd);
    '''

options = webdriver.ChromeOptions()
profile = "C:\\Users\\nicvaldy\\AppData\\Local\\Google\\Chrome\\User Data\\Profile 38"
options.add_argument(f"user-data=dir={profile}",)
mobile_emulation = {
    "deviceMetrics": { "width": 360, "height": 640, "pixelRatio": 3.0 },
    "userAgent": "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75 Mobile Safari/535.19" }
chrome_options = webdriver.ChromeOptions()

chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)

driver = webdriver.Chrome(chrome_options=chrome_options,use_subprocess=True)
driver.get("https://click.discord.com/ls/click?")
driver.execute_script(recreate_localStorage_script)  # Recreating the localStorage Object again, has to be done after every reload
print('token:', driver.execute_script(
    f"return window.localStorage.getItem('token');"))

time.sleep(160)
```

Check key and values

Result

Body:
I am always getting None result when I read value "token" from discord verification link. How can I get token value from localstorage for Chromedriver?

import undetected_chromedriver as webdriver
import time

recreate_localStorage_script = '''
    const iframe = document.createElement('iframe');
    document.head.append(iframe);
    const pd = Object.getOwnPropertyDescriptor(iframe.contentWindow, 'localStorage');
    iframe.remove();
    Object.defineProperty(window, 'localStorage', pd);
    '''

options = webdriver.ChromeOptions()
profile = "C:\\Users\\nicvaldy\\AppData\\Local\\Google\\Chrome\\User Data\\Profile 38"
options.add_argument(f"user-data=dir={profile}",)
mobile_emulation = {
    "deviceMetrics": { "width": 360, "height": 640, "pixelRatio": 3.0 },
    "userAgent": "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75 Mobile Safari/535.19" }
chrome_options = webdriver.ChromeOptions()

chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)

driver = webdriver.Chrome(chrome_options=chrome_options,use_subprocess=True)
driver.get("https://click.discord.com/ls/click?")
driver.execute_script(recreate_localStorage_script)  # Recreating the localStorage Object again, has to be done after every reload
print('token:', driver.execute_script(
    f"return window.localStorage.getItem('token');"))

time.sleep(160)

Check key and values

Result


问:
How to determine the column properties of the results returned by the database in Qt through parameters？
I try to input multiple parameters through the QString.arg method, but the returned result is not what I need, and I don't understand the difference between statement 1 and statement 2?</p>
```<code>`void MainWindow::on_pushButton_clicked()
{
    QString contents=ui->lineEdit->text();    //获取内容
    qryModel=new QSqlQueryModel(this);
    theSelection=new QItemSelectionModel(qryModel);
    QString str="x1,x2";
    qryModel->setQuery(QString("select x1,x2 from test1 where test1.x1='%1'").arg(contents));//Statement1
    qryModel->setQuery(QString("select '%1' from test1 where test1.x1='%2'").arg(str).arg(contents));//Statement2
    ui->tableView->setModel(qryModel);//数据放置进去
}
`
</code>```

Body:
I try to input multiple parameters through the QString.arg method, but the returned result is not what I need, and I don't understand the difference between statement 1 and statement 2?

`void MainWindow::on_pushButton_clicked()
{
    QString contents=ui->lineEdit->text();    //获取内容
    qryModel=new QSqlQueryModel(this);
    theSelection=new QItemSelectionModel(qryModel);
    QString str="x1,x2";
    qryModel->setQuery(QString("select x1,x2 from test1 where test1.x1='%1'").arg(contents));//Statement1
    qryModel->setQuery(QString("select '%1' from test1 where test1.x1='%2'").arg(str).arg(contents));//Statement2
    ui->tableView->setModel(qryModel);//数据放置进去
}
`


问:
Angular 14 always gives "error" even though it's perfoming the action
So i'm trying to make a delete button with Angular and Spring boots. The problem is that when I click in "delete" it says "failed to delete component" BUT IT DELETES IT ANYWAY. I have try an "add button" and it does the same thing.

Here's the typescript:

```<code>`delete(id:number){
  if(id !=undefined){
    this.sExperiencia.delete(id).subscribe(
      data=>{
        this.cargarExperiencia();
        window.location.reload();
      }, err => {
        alert ("failed to delete component")
        window.location.reload();
      }
    )
  }
}`
</code>```

Angular Version: 14.2.4

Body:
So i'm trying to make a delete button with Angular and Spring boots. The problem is that when I click in "delete" it says "failed to delete component" BUT IT DELETES IT ANYWAY. I have try an "add button" and it does the same thing.

Here's the typescript:

`delete(id:number){
  if(id !=undefined){
    this.sExperiencia.delete(id).subscribe(
      data=>{
        this.cargarExperiencia();
        window.location.reload();
      }, err => {
        alert ("failed to delete component")
        window.location.reload();
      }
    )
  }
}`

Angular Version: 14.2.4


问:
Adaptive momentum in ANN optimization
In SGD optimization I can not make custom momentum.

I have constructed the ANN model and did optimization with a constant learning rate and momentum. I want the momentum to be changed in each iteration with this function momentum=0.95/(0.95-0.9^epoch). Please, can someone help me to write this part? Thank you. I will really appreciate it.

```<code>import tensorflow as tf
from sklearn.metrics import plot_confusion_matrix

# Let us build a MLP NN
if __name__ == "__main__":

    # build model with 3 layers: 31 -> 32 -> 5
    model = tf.keras.models.Sequential([
      tf.keras.layers.Dense(31, activation="tanh"),
      tf.keras.layers.Dense(32, activation="tanh"),
      tf.keras.layers.Dense(5, activation="softmax")
    ])

    # choose optimiser
    optimizer = tf.keras.optimizers.SGD(learning_rate=a,momentum=0.75)

    # compile model
    model.compile(optimizer=optimizer, loss='mse',metrics=['accuracy'])

    # train model
    history=model.fit(X_train, y_train_labeled, epochs=70, batch_size=64)

    # After passing X_test to a prediction model it will compare it with y_test then builds CONFUSION MATRIX

    #disp=plot_confusion_matrix(model,X_test,y_test_labeled,cmap="Blues",values_format='.3g')

    # evaluate model on test set
    print("Results of Test set:")
    history_validation=model.evaluate(X_test, y_test_labeled, verbose=2)
</code>```

Title: Adaptive momentum in ANN optimization

Body:
In SGD optimization I can not make custom momentum.

I have constructed the ANN model and did optimization with a constant learning rate and momentum. I want the momentum to be changed in each iteration with this function momentum=0.95/(0.95-0.9^epoch). Please, can someone help me to write this part? Thank you. I will really appreciate it.

import tensorflow as tf
from sklearn.metrics import plot_confusion_matrix

# Let us build a MLP NN
if __name__ == "__main__":

    # build model with 3 layers: 31 -> 32 -> 5
    model = tf.keras.models.Sequential([
      tf.keras.layers.Dense(31, activation="tanh"),
      tf.keras.layers.Dense(32, activation="tanh"),
      tf.keras.layers.Dense(5, activation="softmax")
    ])

    # choose optimiser
    optimizer = tf.keras.optimizers.SGD(learning_rate=a,momentum=0.75)

    # compile model
    model.compile(optimizer=optimizer, loss='mse',metrics=['accuracy'])

    # train model
    history=model.fit(X_train, y_train_labeled, epochs=70, batch_size=64)

    # After passing X_test to a prediction model it will compare it with y_test then builds CONFUSION MATRIX

    #disp=plot_confusion_matrix(model,X_test,y_test_labeled,cmap="Blues",values_format='.3g')

    # evaluate model on test set
    print("Results of Test set:")
    history_validation=model.evaluate(X_test, y_test_labeled, verbose=2)


问:
Does Google play for AR services support Xiaomi 11T pro?
Does Google play for AR services support Xiaomi 11T pro?

I am playing a game that needs AR, but it seems the AR installed does not work, and cannot update.

Wanted to ask if Google play for AR services support Xiaomi 11T pro?

If not yet, would it be included before Dec 31, 2022?

tried following instructions in the game, but just prompt me to update the Google Play for AR (without update button), then gave me a black screen, then stopped the game.


问:
How do I map Tab to Esc in IdeaVim?
I would like to map the Tab key to exiting the insert mode in idea vim.

Here is what I currently have in my .ideavimrc file:

```<code>nnoremap <Tab> <Esc>
vnoremap <Tab> <Esc>gV
onoremap <Tab> <Esc>
cnoremap <Tab> <C-C><Esc>
inoremap <Tab> <Esc>`^
inoremap <Leader><Tab> <Tab>
</code>```

This seems not to work on IdeaVim but works perfectly fine in vim.

After searching in the IdeaVim repository, I found that  was in the lookupkeys. I removed it by doing:

```<code>set lookupkeys=<Down>,<Up>,<Enter>,<Left>,<Right>,<C-Down>,<C-Up>,<PageUp>,<PageDown>,<C-J>,<C-Q>
</code>```

but still nothing.

What is the correct way of mapping Tab to Esc in IdeaVim?

Title: How do I map Tab to Esc in IdeaVim?

Body:
I would like to map the Tab key to exiting the insert mode in idea vim.

Here is what I currently have in my .ideavimrc file:

nnoremap <Tab> <Esc>
vnoremap <Tab> <Esc>gV
onoremap <Tab> <Esc>
cnoremap <Tab> <C-C><Esc>
inoremap <Tab> <Esc>`^
inoremap <Leader><Tab> <Tab>

This seems not to work on IdeaVim but works perfectly fine in vim.

After searching in the IdeaVim repository, I found that  was in the lookupkeys. I removed it by doing:

set lookupkeys=<Down>,<Up>,<Enter>,<Left>,<Right>,<C-Down>,<C-Up>,<PageUp>,<PageDown>,<C-J>,<C-Q>

but still nothing.

What is the correct way of mapping Tab to Esc in IdeaVim?