问:
Failed to connect: Error: connect: getConnection: All configured authentication methods failed
I develop a function for my bot discord, and I want to connect to a sftp server with the module ssh2-sftp-client.
For my project, I have several directories, but for my case, I only need to give you 2, in the folder "functions", there are two files, sftpConnection.js and react.js, and in the folder "events", there is the file messageCreate.js, messageCreate is used to call the react.js file, which has the function sftpScrapper, which is used to use sftpConnection, where there is a class SFTPClient, which is used to connect to a sftp server.
The problem is that when I try to make the sftp connection, my console tells me the error:

Connecting to "hostName":22
Failed to connect: Error: connect: getConnection: All configured authentication methods failed
    at SftpClient.fmtError (E:\Perso\PHOTOSHOP\CODING\discord.js v14\Lt-Col. Tanya\node_modules\ssh2-sftp-client\src\index.js:111:22)
    at SftpClient.connect (E:\Perso\PHOTOSHOP\CODING\discord.js v14\Lt-Col. Tanya\node_modules\ssh2-sftp-client\src\index.js:249:37)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async SFTPClient.connect (E:\Perso\PHOTOSHOP\CODING\discord.js v14\Lt-Col. Tanya\functions\sftpConnection.js:10:13)
    at async Object.sftpScraper (E:\Perso\PHOTOSHOP\CODING\discord.js v14\Lt-Col. Tanya\functions\react.js:259:17)
    at async module.exports (E:\Perso\PHOTOSHOP\CODING\discord.js v14\Lt-Col. Tanya\events\messageCreate.js:21:5) {
  code: 'ERR_GENERIC_CLIENT',
  custom: true
}
node:events:491
      throw er; // Unhandled 'error' event
      ^

    at Object.sftpScraper (E:\Perso\PHOTOSHOP\CODING\discord.js v14\Lt-Col. Tanya\functions\react.js:266:34)
    at async module.exports (E:\Perso\PHOTOSHOP\CODING\discord.js v14\Lt-Col. Tanya\events\messageCreate.js:21:5)
Emitted 'error' event on Client instance at:
    at emitUnhandledRejectionOrErr (node:events:394:10)
    at process.processTicksAndRejections (node:internal/process/task_queues:84:21)

Node.js v18.10.0
[nodemon] app crashed - waiting for file changes before starting...```
</code>```

The code :

sftpConnection.js :

const ssh = require("ssh2-sftp-client")

class SFTPClient {
    constructor() {
        this.client = new ssh();
    }
    async connect(options) {
        console.log(`Connecting to ${options.host}:${options.port}`);
        try {
            await this.client.connect(options);
        } catch (err) {
            console.log('Failed to connect:', err);
        }
    }

    async disconnect() {
        await this.client.end();
    }

    async listFiles(remoteDir, fileGlob) {
        console.log(`Listing ${remoteDir} ...`);
        let fileObjects;
        try {
          fileObjects = await this.client.list(remoteDir, fileGlob);
        } catch (err) {
          console.log('Listing failed:', err);
        }

        const fileNames = [];

        for (const file of fileObjects) {
          if (file.type === 'd') {
            console.log(`${new Date(file.modifyTime).toISOString()} PRE ${file.name}`);
          } else {
            console.log(`${new Date(file.modifyTime).toISOString()} ${file.size} ${file.name}`);
          }

          fileNames.push(file.name);
        }

        return fileNames;
      }

};

module.exports = SFTPClient```
</code>```

react.js :

const Discord = require("discord.js");
const { connect } = require("http2");
const fs = require("fs");
// const fetch = require('node-fetch');
// const config = require("../Storage/config.json");
const https = require('https');
const sftp = require("./sftpConnection.js");
const sftpLog = require("../Storage/sftpLog.json");
const SFTPClient = require("./sftpConnection.js");
// const { client } = require("tenorjs");

var functions = {
sftpScraper: async function(bot, message) {
switch (message.content) {
case "test-sftp":
const {hostCharon, ipCharon, usernameCharon, passwordCharon} = sftpLog\["piccoma-charon"\]\[0\];
const {hostMakma, ipMakma, usernameMakma, passwordMakma} = sftpLog\["piccoma-makma"\]\[0\]

                const sftpClient = new SFTPClient();

                await sftpClient.connect({
                    host: hostCharon,
                    port: "22",
                    username: usernameCharon,
                    passwordCharon: passwordCharon,
                    tryKeyboard: true,
                })

                await sftpClient.listFiles(".");

                break;

            default:
                break;
        }

    }

}

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

and the react.js is launched on messageCreate.js :

const config = require("../Storage/config.json");
module.exports = async(bot, message) => {
    ; const prefix = config.prefix;
    const owners = [''];
    const wompServer = ['']
    bot.user.setActivity(""); // Marque en status ""

    const args = message.content.split(/ +/g);
    const command = args.shift().slice(prefix.length).toLowerCase();
    const cmd = bot.commands.get(command) || bot.aliases.get(command);

    const reactFunction = require('../functions/react.js');
    await reactFunction.fakeGift(bot, message);
    await reactFunction.sftpScraper(bot, message);
cmd.run(bot, message, args).catch(e => { return console.log(e) });

    bot.logger.log(`[${message.member.user.tag}] a utilisé la commande [${cmd.help.name}]`).catch(e => { return console.log(e) });

    message.delete()

}```
</code>```

I've tried to put a tryKeyboard: true, but i don't know how to use it, and the methode i have seen, doesn't work for me, because i can't do a sftpClient.on()...

Can you propose to me a way to fix this problem which work with my code ?

Body:
I develop a function for my bot discord, and I want to connect to a sftp server with the module ssh2-sftp-client.
For my project, I have several directories, but for my case, I only need to give you 2, in the folder "functions", there are two files, sftpConnection.js and react.js, and in the folder "events", there is the file messageCreate.js, messageCreate is used to call the react.js file, which has the function sftpScrapper, which is used to use sftpConnection, where there is a class SFTPClient, which is used to connect to a sftp server.
The problem is that when I try to make the sftp connection, my console tells me the error:

Connecting to "hostName":22
Failed to connect: Error: connect: getConnection: All configured authentication methods failed
    at SftpClient.fmtError (E:\Perso\PHOTOSHOP\CODING\discord.js v14\Lt-Col. Tanya\node_modules\ssh2-sftp-client\src\index.js:111:22)
    at SftpClient.connect (E:\Perso\PHOTOSHOP\CODING\discord.js v14\Lt-Col. Tanya\node_modules\ssh2-sftp-client\src\index.js:249:37)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async SFTPClient.connect (E:\Perso\PHOTOSHOP\CODING\discord.js v14\Lt-Col. Tanya\functions\sftpConnection.js:10:13)
    at async Object.sftpScraper (E:\Perso\PHOTOSHOP\CODING\discord.js v14\Lt-Col. Tanya\functions\react.js:259:17)
    at async module.exports (E:\Perso\PHOTOSHOP\CODING\discord.js v14\Lt-Col. Tanya\events\messageCreate.js:21:5) {
  code: 'ERR_GENERIC_CLIENT',
  custom: true
}
node:events:491
      throw er; // Unhandled 'error' event
      ^

    at Object.sftpScraper (E:\Perso\PHOTOSHOP\CODING\discord.js v14\Lt-Col. Tanya\functions\react.js:266:34)
    at async module.exports (E:\Perso\PHOTOSHOP\CODING\discord.js v14\Lt-Col. Tanya\events\messageCreate.js:21:5)
Emitted 'error' event on Client instance at:
    at emitUnhandledRejectionOrErr (node:events:394:10)
    at process.processTicksAndRejections (node:internal/process/task_queues:84:21)

Node.js v18.10.0
[nodemon] app crashed - waiting for file changes before starting...```
</code></pre>
<p>The code :</p>
<p>sftpConnection.js :</p>
<pre class="lang-js prettyprint-override"><code>const ssh = require("ssh2-sftp-client")

class SFTPClient {
    constructor() {
        this.client = new ssh();
    }
    async connect(options) {
        console.log(`Connecting to ${options.host}:${options.port}`);
        try {
            await this.client.connect(options);
        } catch (err) {
            console.log('Failed to connect:', err);
        }
    }

    async disconnect() {
        await this.client.end();
    }

    async listFiles(remoteDir, fileGlob) {
        console.log(`Listing ${remoteDir} ...`);
        let fileObjects;
        try {
          fileObjects = await this.client.list(remoteDir, fileGlob);
        } catch (err) {
          console.log('Listing failed:', err);
        }

        const fileNames = [];

        for (const file of fileObjects) {
          if (file.type === 'd') {
            console.log(`${new Date(file.modifyTime).toISOString()} PRE ${file.name}`);
          } else {
            console.log(`${new Date(file.modifyTime).toISOString()} ${file.size} ${file.name}`);
          }

          fileNames.push(file.name);
        }

        return fileNames;
      }

};

module.exports = SFTPClient```

react.js :

const Discord = require("discord.js");
const { connect } = require("http2");
const fs = require("fs");
// const fetch = require('node-fetch');
// const config = require("../Storage/config.json");
const https = require('https');
const sftp = require("./sftpConnection.js");
const sftpLog = require("../Storage/sftpLog.json");
const SFTPClient = require("./sftpConnection.js");
// const { client } = require("tenorjs");

var functions = {
sftpScraper: async function(bot, message) {
switch (message.content) {
case "test-sftp":
const {hostCharon, ipCharon, usernameCharon, passwordCharon} = sftpLog\["piccoma-charon"\]\[0\];
const {hostMakma, ipMakma, usernameMakma, passwordMakma} = sftpLog\["piccoma-makma"\]\[0\]

                const sftpClient = new SFTPClient();

                await sftpClient.connect({
                    host: hostCharon,
                    port: "22",
                    username: usernameCharon,
                    passwordCharon: passwordCharon,
                    tryKeyboard: true,
                })

                await sftpClient.listFiles(".");

                break;

            default:
                break;
        }

    }

}

module.exports = functions;```
</code></pre>
<p>and the react.js is launched on messageCreate.js :</p>
<pre class="lang-js prettyprint-override"><code>const config = require("../Storage/config.json");
module.exports = async(bot, message) => {
    ; const prefix = config.prefix;
    const owners = [''];
    const wompServer = ['']
    bot.user.setActivity(""); // Marque en status ""

    const args = message.content.split(/ +/g);
    const command = args.shift().slice(prefix.length).toLowerCase();
    const cmd = bot.commands.get(command) || bot.aliases.get(command);

    const reactFunction = require('../functions/react.js');
    await reactFunction.fakeGift(bot, message);
    await reactFunction.sftpScraper(bot, message);
cmd.run(bot, message, args).catch(e => { return console.log(e) });

    bot.logger.log(`[${message.member.user.tag}] a utilisé la commande [${cmd.help.name}]`).catch(e => { return console.log(e) });

    message.delete()

}```

I've tried to put a tryKeyboard: true, but i don't know how to use it, and the methode i have seen, doesn't work for me, because i can't do a sftpClient.on()...

Can you propose to me a way to fix this problem which work with my code ?


来源: stackexchange

问:
error 403 when requesting to activate the kun code, I think it's in the data but I can't understand
```<code>import requests
from hashlib import sha384
import time
import json
import hmac

class Wrapper:
    def __init__(self,
        public_key: str = None,
        private_key: str = None):
        self.public_key = public_key
        self.private_key = private_key
        self.DEFAULT_HEADERS = {
        "Accept": "application/json",
        "Content-Type": "application/json",
    }

    def _request(self, uri: str, path: str, body: dict):
        round(time.time() * 1000)
        nonce = round(time.time() * 1000)
        str_nonce = str(nonce)
        print(str_nonce, nonce)
        body = json.dumps(body)
        headers = self.DEFAULT_HEADERS.copy()
        headers["kun-nonce"] = str_nonce
        headers["kun-apikey"] = self.public_key
        headers["kun-signature"] = self._sign(
            path, str_nonce, body
        )
        response = requests.put(uri, json=body, headers=headers)
        json_response = response.json()
        return json_response

    def load(self, code):
        body = {"code": code}
        return self._request("https://api.kuna.io:443/v3/auth/kuna_codes/redeem", "/v3/auth/kuna_codes/redeem", body)
    def _sign(self, path: str, nonce: str, body: str) -> str:
        payload = "{}{}{}".format(path, nonce, body)
        print(nonce)
        payload_bin = payload.encode("ascii")
        private_key_bin = self.private_key.encode("ascii")
        sign = hmac.new(private_key_bin, payload_bin, sha384)
        return sign.hexdigest()

</code>```

Please help I don't understand why it doesn't work.
Expecting value: line 1 column 1 (char 0)
<Response [403]> Forbidden
maybe I'm not passing the code correctly or something else is wrong

ContentLicense: CC BY-SA 4.0

Body:
import requests
from hashlib import sha384
import time
import json
import hmac

class Wrapper:
    def __init__(self,
        public_key: str = None,
        private_key: str = None):
        self.public_key = public_key
        self.private_key = private_key
        self.DEFAULT_HEADERS = {
        "Accept": "application/json",
        "Content-Type": "application/json",
    }

    def _request(self, uri: str, path: str, body: dict):
        round(time.time() * 1000)
        nonce = round(time.time() * 1000)
        str_nonce = str(nonce)
        print(str_nonce, nonce)
        body = json.dumps(body)
        headers = self.DEFAULT_HEADERS.copy()
        headers["kun-nonce"] = str_nonce
        headers["kun-apikey"] = self.public_key
        headers["kun-signature"] = self._sign(
            path, str_nonce, body
        )
        response = requests.put(uri, json=body, headers=headers)
        json_response = response.json()
        return json_response

    def load(self, code):
        body = {"code": code}
        return self._request("https://api.kuna.io:443/v3/auth/kuna_codes/redeem", "/v3/auth/kuna_codes/redeem", body)
    def _sign(self, path: str, nonce: str, body: str) -> str:
        payload = "{}{}{}".format(path, nonce, body)
        print(nonce)
        payload_bin = payload.encode("ascii")
        private_key_bin = self.private_key.encode("ascii")
        sign = hmac.new(private_key_bin, payload_bin, sha384)
        return sign.hexdigest()

Please help I don't understand why it doesn't work.
Expecting value: line 1 column 1 (char 0)
<Response [403]> Forbidden
maybe I'm not passing the code correctly or something else is wrong


问:
keycloak user registration settings per client
I'm building an application which requires two types of users, one is customer with less privileges and other one is for administration. I have two different frontend applications that uses same spring boot rest api.

As far as I understand, I created two clients (customer-app and admin-app) and my frontend apps use these clients for authentication.

I want to set default role when user registration happen per client. You can set default group and roles under "realm settings > user registration >
default groups & roles" but this not enough for me. I want to say if user registered to client "customer-app" assign to customer role and if registered to client "admin-app" assign to admin role.

And finally, I can decode jwt which stores user type role (customer & admin) to determine users' permissions.

I can't find a way to do this, I may have misunderstood some keycloak concepts.

Waiting for your help...


问:
Searching a dataset for face recognition
I'm working on facial recognition project.
can anyone give me a dataset for facial recognition?

find a dataset of faces for facial recognition images and/or videos


问:
Can't join @Controller and Thymeleaf view
At startup, the spring application works with view, but the html code is highlighted in red when it is written, respectively, it is not convenient to look for errors in html, here are photos and code of html and the controller:
(https://i.stack.imgur.com/RDPvL.png)
(https://i.stack.imgur.com/Bm1vQ.png)

```<code>package com.nikita.al_fp.controllers;

import com.nikita.al_fp.entity.Book;
import com.nikita.al_fp.entity.Person;
import com.nikita.al_fp.service.BookService;
import com.nikita.al_fp.service.PersonService;
import com.nikita.al_fp.util.BookValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;

@Controller
@RequestMapping("/book")
public class BookController {

    private final BookValidator bookValidator;
    private final PersonService personService;
    private final BookService bookService;
    public static final String BOOK_REDIRECT_PAGE = "redirect:/book";

    @Autowired
    public BookController(BookValidator bookValidator, PersonService personService, BookService bookService) {
        this.bookValidator = bookValidator;
        this.personService = personService;
        this.bookService = bookService;
        personService.startProgramProcessPerson();
        bookService.startProgramProcessBook();
    }

    @GetMapping
    public String selectBook(Model model) {
        model.addAttribute("books", bookService.findAll());
        return "/book/select_book";
    }
}

</code>```
```<code><!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Select Book</title>
</head>
<body>

<div th:each="book : ${books}">
    <a th:href="@{/book/{id}(id=${book.getId()})}"
       th:text="${book.getName() + ', ' + book.getAuthor() + ', ' + book.getYear()}">book</a>
    <br/>
</div>

<br/>
<hr/>

<a href="/book/new">Add book</a>
<br>
<a href="/people">Show User List</a>

</body>
</html>

</code>```
```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.nikita</groupId>
    <artifactId>al_fp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>al_fp</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>2.0.1.Final</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

</code>```

I tried to find a solution on the Internet, unsuccessfully, but views work when app runned

Body:
At startup, the spring application works with view, but the html code is highlighted in red when it is written, respectively, it is not convenient to look for errors in html, here are photos and code of html and the controller:
(https://i.stack.imgur.com/RDPvL.png)
(https://i.stack.imgur.com/Bm1vQ.png)

package com.nikita.al_fp.controllers;

import com.nikita.al_fp.entity.Book;
import com.nikita.al_fp.entity.Person;
import com.nikita.al_fp.service.BookService;
import com.nikita.al_fp.service.PersonService;
import com.nikita.al_fp.util.BookValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;

@Controller
@RequestMapping("/book")
public class BookController {

    private final BookValidator bookValidator;
    private final PersonService personService;
    private final BookService bookService;
    public static final String BOOK_REDIRECT_PAGE = "redirect:/book";

    @Autowired
    public BookController(BookValidator bookValidator, PersonService personService, BookService bookService) {
        this.bookValidator = bookValidator;
        this.personService = personService;
        this.bookService = bookService;
        personService.startProgramProcessPerson();
        bookService.startProgramProcessBook();
    }

    @GetMapping
    public String selectBook(Model model) {
        model.addAttribute("books", bookService.findAll());
        return "/book/select_book";
    }
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Select Book</title>

    book

Add book

Show User List

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.1</version>
        <relativePath/>
    </parent>
    <groupId>com.nikita</groupId>
    <artifactId>al_fp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>al_fp</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>2.0.1.Final</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

I tried to find a solution on the Internet, unsuccessfully, but views work when app runned


问:
Interaction between multiple Select filters in Bokeh on DataTable
Using the bokeh package I am trying to filter a data table using two (or more) filters. As my data is quite large, I would like the filters to interact with each other so that they only show options that, when combined, will show data instead of an empty table.
The MRE below shows two filters working on a data set. If however you select 'United States' for the country, all potential years are shown, rather than just the two available for the US.

How can I make the select filters work with the others in this regard? I.e. in this MRE have year only show 2008 and 2007 when US is selected.

```<code>from bokeh.layouts import column
from bokeh.models import ColumnDataSource, CustomJS
from bokeh.models.widgets import DataTable, TableColumn, Select
from bokeh.plotting import save, output_file
from pandas_datareader import wb

df = wb.download(indicator='NY.GDP.PCAP.KD', country=['US', 'CA', 'MX'], start=2005, end=2008)
df = df[0:10]
df = df.reset_index()

source = ColumnDataSource(df)
original_source = ColumnDataSource(df)
columns = [
TableColumn(field="country", title="Country"),
TableColumn(field="year", title="Year"),
TableColumn(field="NY.GDP.PCAP.KD", title="NY.GDP.PCAP.KD"),
]
data_table = DataTable(source=source, columns=columns)

# callback code to be used by all the filter widgets
# requires (source, original_source, country_select_obj, year_select_obj, target_object)
combined_callback_code = """
var data = source.data;
var original_data = original_source.data;
var country = country_select_obj.value;
console.log("country: " + country);
var year = year_select_obj.value;
console.log("year: " + year);
for (var key in original_data) {
    data[key] = [];
    for (var i = 0; i < original_data['country'].length; ++i) {
        if ((country === "ALL" || original_data['country'][i] === country) &&
            (year === "ALL" || original_data['year'][i] === year)) {
            data[key].push(original_data[key][i]);
        }
    }
}

source.change.emit();
target_obj.change.emit();
"""

# define the filter widgets, without callbacks for now
country_list = ['ALL'] + df['country'].unique().tolist()
country_select = Select(title="Country:", value=country_list[0], options=country_list)
year_list = ['ALL'] + df['year'].unique().tolist()
year_select = Select(title="Year:", value=year_list[0], options=year_list)

# now define the callback objects now that the filter widgets exist
generic_callback = CustomJS(
    args=dict(source=source,
            original_source=original_source,
            country_select_obj=country_select,
            year_select_obj=year_select,
            target_obj=data_table),
    code=combined_callback_code
)

# finally, connect the callbacks to the filter widgets
country_select.js_on_change('value', generic_callback)
year_select.js_on_change('value', generic_callback)

p = column(country_select,year_select,data_table)
output_file('datatable_filter.html')
save(p)
</code>```

Body:
Using the bokeh package I am trying to filter a data table using two (or more) filters. As my data is quite large, I would like the filters to interact with each other so that they only show options that, when combined, will show data instead of an empty table.
The MRE below shows two filters working on a data set. If however you select 'United States' for the country, all potential years are shown, rather than just the two available for the US.

How can I make the select filters work with the others in this regard? I.e. in this MRE have year only show 2008 and 2007 when US is selected.

from bokeh.layouts import column
from bokeh.models import ColumnDataSource, CustomJS
from bokeh.models.widgets import DataTable, TableColumn, Select
from bokeh.plotting import save, output_file
from pandas_datareader import wb

df = wb.download(indicator='NY.GDP.PCAP.KD', country=['US', 'CA', 'MX'], start=2005, end=2008)
df = df[0:10]
df = df.reset_index()

source = ColumnDataSource(df)
original_source = ColumnDataSource(df)
columns = [
TableColumn(field="country", title="Country"),
TableColumn(field="year", title="Year"),
TableColumn(field="NY.GDP.PCAP.KD", title="NY.GDP.PCAP.KD"),
]
data_table = DataTable(source=source, columns=columns)

# callback code to be used by all the filter widgets
# requires (source, original_source, country_select_obj, year_select_obj, target_object)
combined_callback_code = """
var data = source.data;
var original_data = original_source.data;
var country = country_select_obj.value;
console.log("country: " + country);
var year = year_select_obj.value;
console.log("year: " + year);
for (var key in original_data) {
    data[key] = [];
    for (var i = 0; i < original_data['country'].length; ++i) {
        if ((country === "ALL" || original_data['country'][i] === country) &&
            (year === "ALL" || original_data['year'][i] === year)) {
            data[key].push(original_data[key][i]);
        }
    }
}

source.change.emit();
target_obj.change.emit();
"""

# define the filter widgets, without callbacks for now
country_list = ['ALL'] + df['country'].unique().tolist()
country_select = Select(title="Country:", value=country_list[0], options=country_list)
year_list = ['ALL'] + df['year'].unique().tolist()
year_select = Select(title="Year:", value=year_list[0], options=year_list)

# now define the callback objects now that the filter widgets exist
generic_callback = CustomJS(
    args=dict(source=source,
            original_source=original_source,
            country_select_obj=country_select,
            year_select_obj=year_select,
            target_obj=data_table),
    code=combined_callback_code
)

# finally, connect the callbacks to the filter widgets
country_select.js_on_change('value', generic_callback)
year_select.js_on_change('value', generic_callback)

p = column(country_select,year_select,data_table)
output_file('datatable_filter.html')
save(p)


问:
How does CSS decide implicit animation keyframes?
When an animation is triggered via the javascript API, it requires a list of keyframes. This example is from Vuetify.

const animation = animate(el, [{
  transform: `translate(${x}px, ${y}px) scale(${sx}, ${sy})`,
  opacity: 0
}, {
  transform: '',
}], {
  duration: 225 * speed,
  easing: deceleratedEasing
});
```
<p>These keyframes are implicit, as they do not both include opacity, nor both transform.</p>
<p>On older browswers (i.e., Chrome 69.0), this is a problem, and one needs to be explicit about animation keyframes. Thus, it throws an exception for the above code. However, it works if changed to</p>
<pre class="lang-js prettyprint-override"><code>const animation = animate(el, [{
  transform: `translate(${x}px, ${y}px) scale(${sx}, ${sy})`,
  opacity: 0
}, {
  transform: `translate(${x}px, ${y}px) scale(${sx}, ${sy})`,
  opacity: 1
}], {
  duration: 225 * speed,
  easing: deceleratedEasing
});
</code>```

How does modern CSS decide the values for the implicit keyframes, and how can I find out that information for a generic keyframe with opacity, transform, and offset?

From this page, "Implicit to/from keyframes are supported from Chrome v84".

I tried entering values myself, but I have no idea what the implicit/default keyframes/opacities should be.

Body:
When an animation is triggered via the javascript API, it requires a list of keyframes. This example is from Vuetify.

const animation = animate(el, [{
  transform: `translate(${x}px, ${y}px) scale(${sx}, ${sy})`,
  opacity: 0
}, {
  transform: '',
}], {
  duration: 225 * speed,
  easing: deceleratedEasing
});

These keyframes are implicit, as they do not both include opacity, nor both transform.

On older browswers (i.e., Chrome 69.0), this is a problem, and one needs to be explicit about animation keyframes. Thus, it throws an exception for the above code. However, it works if changed to

const animation = animate(el, [{
  transform: `translate(${x}px, ${y}px) scale(${sx}, ${sy})`,
  opacity: 0
}, {
  transform: `translate(${x}px, ${y}px) scale(${sx}, ${sy})`,
  opacity: 1
}], {
  duration: 225 * speed,
  easing: deceleratedEasing
});

How does modern CSS decide the values for the implicit keyframes, and how can I find out that information for a generic keyframe with opacity, transform, and offset?

From this page, "Implicit to/from keyframes are supported from Chrome v84".

I tried entering values myself, but I have no idea what the implicit/default keyframes/opacities should be.


问:
Iterate through dynamic table in for loop in java
on my project there is dynamically loaded table so each time when we scroll down, table is updating and rowcount starts from 0 or 1 i guess. and i want to iterate through whole table and get specific cell's text from every row. how can i do that? please, help.
what i have done so far is:

```<code>    List<WebElement> currentGridTableRowsList = driver.findElements(
            By.xpath("//table[@role='grid'] //tbody/tr"));

    //print current rows count
    int currentGridTableRows = currentGridTableRowsList.size();
    System.out.println(currentGridTableRows);

    for (WebElement row : currentGridTableRowsList){
        List<WebElement> tdCollection = row.findElements(By.tagName("td"));
        for (WebElement td : tdCollection){
            String cellText = td.getText();

            System.out.println(cellText);
        }
    }
</code>```

currentGridTableRowsList.size() returns current grid number of rows - 10 for example. But attribute aria-rowcount returns 30 rows.
I know there is a snippet

```<code>WebElement element = driver.findElement(By.xpath(“//table[@id = ‘tableID’]/tbody//tr[last()]”));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(“arguments[0].scrollIntoView();”, element);
</code>```

but i don't know how to apply that, how to make correct for loops in Java language, so that when it is end of table (current grid), webdriver will scroll and when it is end of table (aria-rowcount) driver will quit. can you please tell me how to write correct for loop for the table and how to get specific cell value, for example td[2] of each row?

Body:
on my project there is dynamically loaded table so each time when we scroll down, table is updating and rowcount starts from 0 or 1 i guess. and i want to iterate through whole table and get specific cell's text from every row. how can i do that? please, help.
what i have done so far is:

    List<WebElement> currentGridTableRowsList = driver.findElements(
            By.xpath("//table[@role='grid'] //tbody/tr"));

    //print current rows count
    int currentGridTableRows = currentGridTableRowsList.size();
    System.out.println(currentGridTableRows);

    for (WebElement row : currentGridTableRowsList){
        List<WebElement> tdCollection = row.findElements(By.tagName("td"));
        for (WebElement td : tdCollection){
            String cellText = td.getText();

            System.out.println(cellText);
        }
    }

currentGridTableRowsList.size() returns current grid number of rows - 10 for example. But attribute aria-rowcount returns 30 rows.
I know there is a snippet

WebElement element = driver.findElement(By.xpath(“//table[@id = ‘tableID’]/tbody//tr[last()]”));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(“arguments[0].scrollIntoView();”, element);

but i don't know how to apply that, how to make correct for loops in Java language, so that when it is end of table (current grid), webdriver will scroll and when it is end of table (aria-rowcount) driver will quit. can you please tell me how to write correct for loop for the table and how to get specific cell value, for example td[2] of each row?


问:
If these failures are not expected, you can try to debug them by setting error_score='raise'
I'm getting this error and it's still not clear for me why is this happening, for me is because the dataset I'm currently using have some blank spaces because this error repeats a couple times once the code is compiled

```<code>/usr/local/lib/python3.8/dist-packages/sklearn/model_selection/_validation.py:372: FitFailedWarning:
10 fits failed out of a total of 10.
The score on these train-test partitions for these parameters will be set to nan.
If these failures are not expected, you can try to debug them by setting error_score='raise'.

Below are more details about the failures:
--------------------------------------------------------------------------------
10 fits failed with the following error:
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/sklearn/model_selection/_validation.py", line 680, in _fit_and_score
    estimator.fit(X_train, y_train, **fit_params)
  File "/usr/local/lib/python3.8/dist-packages/sklearn/linear_model/_logistic.py", line 1508, in fit
    X, y = self._validate_data(
  File "/usr/local/lib/python3.8/dist-packages/sklearn/base.py", line 581, in _validate_data
    X, y = check_X_y(X, y, **check_params)
  File "/usr/local/lib/python3.8/dist-packages/sklearn/utils/validation.py", line 964, in check_X_y
    X = check_array(
  File "/usr/local/lib/python3.8/dist-packages/sklearn/utils/validation.py", line 746, in check_array
    array = np.asarray(array, order=order, dtype=dtype)
ValueError: could not convert string to float: 'delivered'
</code>```

I'm currently working in Collab so I'll attach the code here if you guys could explain me how to solve it'll be a huge help!

next part of the error, looks like is because the models check

```<code>  warnings.warn(some_fits_failed_message, FitFailedWarning)
LR: nan (nan)
LDA
/usr/local/lib/python3.8/dist-packages/sklearn/model_selection/_validation.py:372: FitFailedWarning:
10 fits failed out of a total of 10.
The score on these train-test partitions for these parameters will be set to nan.
If these failures are not expected, you can try to debug them by setting error_score='raise'.

</code>```

Code I'm using is this one:

```<code>url = "train_set.csv"
names = ['ID', 'order_status', 'order_products_value', 'order_freight_value', 'order_items_qty', 'order_sellers_qty', 'order_purchase_timestamp', 'order_aproved_at', 'order_estimated_delivery_date', 'order_delivered_customer_date', 'customer_city', 'customer_state', 'customer_zip_code_prefix', 'product_category_name_english', 'product_name_lenght', 'product_description_lenght', 'product_photos_qty', 'target']
dataset = read_csv(url, names=names)

print(dataset.shape)

print(dataset.head(100))

print("-----------------------------------------------------------------")

print(dataset.describe())

dataset.plot(kind='line', subplots=True, layout=[12,2], sharex=False, sharey=False)
pyplot.show()

array = dataset.values
X = array[:,0:17]
y = array[:,17]
print(y)
X_train, X_validation, Y_train, Y_validation = train_test_split(X, y, test_size=0.20, random_state=1)

models = []
models.append(('LR', LogisticRegression(solver='liblinear', multi_class='ovr')))
models.append(('LDA', LinearDiscriminantAnalysis()))
models.append(('KNN', KNeighborsClassifier()))
models.append(('CART', DecisionTreeClassifier()))
models.append(('NB', GaussianNB()))
models.append(('SVM', SVC(gamma='auto')))

# Here is where the errors are shown

results = []
names = []
print("---- X - Train ---------")
print(X_train)
print(Y_train)

for name, model in models:
    kfold = StratifiedKFold(n_splits=10, random_state=1, shuffle=True)
    print(name)
    cv_results = cross_val_score(model, X_train, Y_train, cv=kfold.get_n_splits(X_train, Y_train), scoring='accuracy')
    results.append(cv_results)
    names.append(name)
    print('%s: %f (%f)' % (name, cv_results.mean(), cv_results.std()))

</code>```

Thanks a bunch!

Body:
I'm getting this error and it's still not clear for me why is this happening, for me is because the dataset I'm currently using have some blank spaces because this error repeats a couple times once the code is compiled

/usr/local/lib/python3.8/dist-packages/sklearn/model_selection/_validation.py:372: FitFailedWarning:
10 fits failed out of a total of 10.
The score on these train-test partitions for these parameters will be set to nan.
If these failures are not expected, you can try to debug them by setting error_score='raise'.

Below are more details about the failures:
--------------------------------------------------------------------------------
10 fits failed with the following error:
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/sklearn/model_selection/_validation.py", line 680, in _fit_and_score
    estimator.fit(X_train, y_train, **fit_params)
  File "/usr/local/lib/python3.8/dist-packages/sklearn/linear_model/_logistic.py", line 1508, in fit
    X, y = self._validate_data(
  File "/usr/local/lib/python3.8/dist-packages/sklearn/base.py", line 581, in _validate_data
    X, y = check_X_y(X, y, **check_params)
  File "/usr/local/lib/python3.8/dist-packages/sklearn/utils/validation.py", line 964, in check_X_y
    X = check_array(
  File "/usr/local/lib/python3.8/dist-packages/sklearn/utils/validation.py", line 746, in check_array
    array = np.asarray(array, order=order, dtype=dtype)
ValueError: could not convert string to float: 'delivered'

I'm currently working in Collab so I'll attach the code here if you guys could explain me how to solve it'll be a huge help!

next part of the error, looks like is because the models check

  warnings.warn(some_fits_failed_message, FitFailedWarning)
LR: nan (nan)
LDA
/usr/local/lib/python3.8/dist-packages/sklearn/model_selection/_validation.py:372: FitFailedWarning:
10 fits failed out of a total of 10.
The score on these train-test partitions for these parameters will be set to nan.
If these failures are not expected, you can try to debug them by setting error_score='raise'.

Code I'm using is this one:

url = "train_set.csv"
names = ['ID', 'order_status', 'order_products_value', 'order_freight_value', 'order_items_qty', 'order_sellers_qty', 'order_purchase_timestamp', 'order_aproved_at', 'order_estimated_delivery_date', 'order_delivered_customer_date', 'customer_city', 'customer_state', 'customer_zip_code_prefix', 'product_category_name_english', 'product_name_lenght', 'product_description_lenght', 'product_photos_qty', 'target']
dataset = read_csv(url, names=names)

print(dataset.shape)

print(dataset.head(100))

print("-----------------------------------------------------------------")

print(dataset.describe())

dataset.plot(kind='line', subplots=True, layout=[12,2], sharex=False, sharey=False)
pyplot.show()

array = dataset.values
X = array[:,0:17]
y = array[:,17]
print(y)
X_train, X_validation, Y_train, Y_validation = train_test_split(X, y, test_size=0.20, random_state=1)

models = []
models.append(('LR', LogisticRegression(solver='liblinear', multi_class='ovr')))
models.append(('LDA', LinearDiscriminantAnalysis()))
models.append(('KNN', KNeighborsClassifier()))
models.append(('CART', DecisionTreeClassifier()))
models.append(('NB', GaussianNB()))
models.append(('SVM', SVC(gamma='auto')))

# Here is where the errors are shown

results = []
names = []
print("---- X - Train ---------")
print(X_train)
print(Y_train)

for name, model in models:
    kfold = StratifiedKFold(n_splits=10, random_state=1, shuffle=True)
    print(name)
    cv_results = cross_val_score(model, X_train, Y_train, cv=kfold.get_n_splits(X_train, Y_train), scoring='accuracy')
    results.append(cv_results)
    names.append(name)
    print('%s: %f (%f)' % (name, cv_results.mean(), cv_results.std()))

Thanks a bunch!


问:
How can I capture panorama image in flutter?
When I open camera in flutter it only opens with option of simple image capture but I to need to open camera with option of panorama and then save it.

I was expecting to open camera in flutter with all options of camera in device but it only gives option to capture simple images


问:
React router version 6.4
I wanted to be able to check a task in a todo so to capture its state as check and save it to my backend but when I tried it saved an object with key checked and value "on" yet I wanted the value to be true or false. So I was using a new hook useFetcher in react router version 6.4. Below is my code for the checkbox Element. If anyone can help make the send form data using useFetcher I will be grateful.

```<code>import React from "react";
import { useFetcher } from "react-router-dom";

const Checkbox = ({ task }) => {
  const toggle = useFetcher();
  const checked = toggle.formData
    ? toggle.formData.get("checked") === "on"
    : task.checked;
  return (
    <toggle.Form method="put" action={`tasks/${task.id}/edit`}>
      <input
        name="checked"
        type="checkbox"
        checked={checked}
        onChange={(e) => toggle.submit(e.target.form)}
        className="checkbox"
      />
      <label>
        <span className="custom-checkbox"></span>
      </label>
    </toggle.Form>
  );
};
export default Checkbox;
</code>```

That is what i genuinely tried, Its four days now but I have failed,

Title: React router version 6.4

Body:
I wanted to be able to check a task in a todo so to capture its state as check and save it to my backend but when I tried it saved an object with key checked and value "on" yet I wanted the value to be true or false. So I was using a new hook useFetcher in react router version 6.4. Below is my code for the checkbox Element. If anyone can help make the send form data using useFetcher I will be grateful.

import React from "react";
import { useFetcher } from "react-router-dom";

const Checkbox = ({ task }) => {
  const toggle = useFetcher();
  const checked = toggle.formData
    ? toggle.formData.get("checked") === "on"
    : task.checked;
  return (
    <toggle.Form method="put" action={`tasks/${task.id}/edit`}>
      <input
        name="checked"
        type="checkbox"
        checked={checked}
        onChange={(e) => toggle.submit(e.target.form)}
        className="checkbox"
      />

    </toggle.Form>
  );
};
export default Checkbox;

That is what i genuinely tried, Its four days now but I have failed,


问:
(uncaught exception)TypeError: fs.existsSync is not a function
I have the following code to try to save the URL file temporarily and then call it in a test, I am using selectFile command from cypress.
cy.get('input[type="file"]').selectFile({
contents: fileType
}, { force: true }
});

but I get the error:
TypeError: fs.existsSync is not a function

I added const fs = require('fs');

```<code>getFile (format, directory = 'files', url = null) {
    if (!url) {
        url = 'https://file-examples.com/wp-content/uploads/2017/10/file_example_PNG_500kB.png';
    }
    return new Promise((resolve, reject) => {
        const directoryPath = path.join(__dirname, `/../../tmp/${directory}`);
        const filePath = path.join(directoryPath, `/file.${format}`);
        // Check if the file already exists
        if (!fs.existsSync(filePath)) {
            getBuffer(url).then((buffer) => {
                fs.mkdirSync(directoryPath, { recursive: true });
                // Save the file
                fs.writeFile(filePath, buffer, 'binary', () => {
                    resolve(filePath);
                });
            });
        } else {
            resolve(filePath);
        }
    });
}
</code>```

Body:
I have the following code to try to save the URL file temporarily and then call it in a test, I am using selectFile command from cypress.
cy.get('input[type="file"]').selectFile({
contents: fileType
}, { force: true }
});

but I get the error:
TypeError: fs.existsSync is not a function

I added const fs = require('fs');

getFile (format, directory = 'files', url = null) {
    if (!url) {
        url = 'https://file-examples.com/wp-content/uploads/2017/10/file_example_PNG_500kB.png';
    }
    return new Promise((resolve, reject) => {
        const directoryPath = path.join(__dirname, `/../../tmp/${directory}`);
        const filePath = path.join(directoryPath, `/file.${format}`);
        // Check if the file already exists
        if (!fs.existsSync(filePath)) {
            getBuffer(url).then((buffer) => {
                fs.mkdirSync(directoryPath, { recursive: true });
                // Save the file
                fs.writeFile(filePath, buffer, 'binary', () => {
                    resolve(filePath);
                });
            });
        } else {
            resolve(filePath);
        }
    });
}


问:
Chrome and Edge blocks printing but on firefox it works
While I am in the browser page, https://mycompany.com/office365-editor/some-file-id, where I can edit and view some office document, I want to also use the printing functionality. So I click on print and see a pop up :  but after I click on "Open PDF" a new tab in the browser opens with following error message:

ffc-word-edit.officeapps.live.com ist gesperrt
Diese Seite wurde von Chrome blockiert
ERR_BLOCKED_BY_CLIENT

I only experience this behavior on Chrome and Edge. On Firebox or Safari it just works.

My guess it has something to do with the chrome ad blocker.

When I look at the network tab and find the request
https://ffc-word-edit.officeapps.live.com/we/WordViewer/request.pdf?sometokens
and copy it manually in another tab, I see a pdf ready to print where I can choose the printer as I expected to be in the first place.


问:
How to change facets fill color in theme?
I am trying to prepare a ggplot in r using the below data,

```<code>Product <- c(rep(c("Reference", "Test"), each = 500))
Value <- c(runif(min = 10, max = 100, n = 600),runif(min =20, max = 80, n = 400))
Method <- c(rep(c("Mehtod A", "Method B", "Method C", "Method D"), times = 250))
df <- data.frame(Product, Value, Method)
</code>```

What I have already prepare looks like the below,

```<code>ggplot(df, aes(x=Product, y=Value)) +
  geom_violin(aes(color= Product),
              fill = "gray80",
              size = 0.7,
              alpha = .1,
              trim = F,
              na.rm = T)+
  geom_sina(aes(color= Product),
            alpha = 0.3,
            na.rm = T)+
  facet_grid(cols = vars(Method),
             scales = "free")+
  geom_signif(test = "wilcox.test",
              test.args = list(ref.group = "Reference"),
              comparisons = list(c("Test", "Reference")),
              map_signif_level= function(p) sprintf("p = %.3g", p),
              y_position = 130,
              na.rm = T)+
  labs(x="",
       y="Value",
       title = toupper("Product Study"),
       subtitle = "Values per product for different methods",
       caption = "Data: Runif",
       tag = "Figure. 1")+
  scale_y_continuous(breaks = seq(0, 100, 20),
                     minor_breaks = seq(0, 100, 10))+
  guides(color = guide_legend(override.aes = list(size = 6)))+
  theme(axis.title.y = element_text(size=10,
                                    face="bold"),
        axis.text.y = element_text(size=10,
                                   face="bold"),
        axis.text.x = element_text(size=10,
                                   face="bold"),
        plot.background = element_rect(fill = "white"),
        panel.background =  element_blank(),
        axis.line.x = element_line(color = "grey"),
        axis.line.y = element_line(color = "grey"),
        axis.ticks.y = element_line(color = "grey"),
        panel.border =  element_rect(fill = "NA",
                                     colour = "darkgrey"),
        panel.grid.major = element_line(size = .5,
                                        linetype = "solid"),
        panel.grid.minor = element_line(size = .25,
                                        linetype = "solid"),
        panel.grid.major.x = element_line(color = "NA"),
        panel.grid.major.y = element_line(color = "grey"),
        panel.grid.minor.x = element_line(color = "NA"),
        panel.grid.minor.y = element_line(color = "grey90"),
        strip.background = element_rect(fill = "lightgrey",
                                        linetype = "solid",
                                        color = "darkgrey"),
        strip.text = element_text(size=10,
                                  face="bold"))
</code>```

but what I would like to do is to change the bellow theme element to something like,

```<code>strip.background = element_rect(fill = Method,
                                        linetype = "solid",
                                        color = "darkgrey")
</code>```

so as to change the facets color based on the different Method (from df).

Unfortunately this doesn't work and sets the fill color to black for all of them!!!

Any help?
Thanks

Body:
I am trying to prepare a ggplot in r using the below data,

Product <- c(rep(c("Reference", "Test"), each = 500))
Value <- c(runif(min = 10, max = 100, n = 600),runif(min =20, max = 80, n = 400))
Method <- c(rep(c("Mehtod A", "Method B", "Method C", "Method D"), times = 250))
df <- data.frame(Product, Value, Method)

What I have already prepare looks like the below,

ggplot(df, aes(x=Product, y=Value)) +
  geom_violin(aes(color= Product),
              fill = "gray80",
              size = 0.7,
              alpha = .1,
              trim = F,
              na.rm = T)+
  geom_sina(aes(color= Product),
            alpha = 0.3,
            na.rm = T)+
  facet_grid(cols = vars(Method),
             scales = "free")+
  geom_signif(test = "wilcox.test",
              test.args = list(ref.group = "Reference"),
              comparisons = list(c("Test", "Reference")),
              map_signif_level= function(p) sprintf("p = %.3g", p),
              y_position = 130,
              na.rm = T)+
  labs(x="",
       y="Value",
       title = toupper("Product Study"),
       subtitle = "Values per product for different methods",
       caption = "Data: Runif",
       tag = "Figure. 1")+
  scale_y_continuous(breaks = seq(0, 100, 20),
                     minor_breaks = seq(0, 100, 10))+
  guides(color = guide_legend(override.aes = list(size = 6)))+
  theme(axis.title.y = element_text(size=10,
                                    face="bold"),
        axis.text.y = element_text(size=10,
                                   face="bold"),
        axis.text.x = element_text(size=10,
                                   face="bold"),
        plot.background = element_rect(fill = "white"),
        panel.background =  element_blank(),
        axis.line.x = element_line(color = "grey"),
        axis.line.y = element_line(color = "grey"),
        axis.ticks.y = element_line(color = "grey"),
        panel.border =  element_rect(fill = "NA",
                                     colour = "darkgrey"),
        panel.grid.major = element_line(size = .5,
                                        linetype = "solid"),
        panel.grid.minor = element_line(size = .25,
                                        linetype = "solid"),
        panel.grid.major.x = element_line(color = "NA"),
        panel.grid.major.y = element_line(color = "grey"),
        panel.grid.minor.x = element_line(color = "NA"),
        panel.grid.minor.y = element_line(color = "grey90"),
        strip.background = element_rect(fill = "lightgrey",
                                        linetype = "solid",
                                        color = "darkgrey"),
        strip.text = element_text(size=10,
                                  face="bold"))

but what I would like to do is to change the bellow theme element to something like,

strip.background = element_rect(fill = Method,
                                        linetype = "solid",
                                        color = "darkgrey")

so as to change the facets color based on the different Method (from df).

Unfortunately this doesn't work and sets the fill color to black for all of them!!!

Any help?
Thanks


问:
Jetpack compose canvas - how to fetch element by text on Android test
I'ld like to fetch element draw into a jetpack compose canvas with drawText.

My usual composeTestRule.onNodeWithText does not found any elements, even when I used useUnmergedTree parameter

Thanks for your help


问:
Android Does not stay connected to ESP8266 in Soft Ap mode
So basically I'm creating a Wireless Weight Scale using a esp. I have built a android app that pulls the data from esp and displays and logs into a local database.
Problem I'm facing is that the wifi does not stay connected in my android device as it does not have access to the internet.

I have tried using multiple devices from various manufactures. In some there is a way to turn of "WiFi Assitant" or "Smart WiFi" but even with those turned off, It automatically switches to a network with active internet access or mobile data.
I have tried to forcefully connect to the esp ssid from inside my app but as most of the apis are depreceated on android 10 onwards, that does'nt work either.
Is there anything that can be done in this matter or do I have to switch to bluetooth.


问:
How to solve partial move error when accessing struct fields?
I'm using a field of the struct ClientError (implemented in the Solana client):

```<code>#[derive(Error, Debug)]
#[error("{kind}")]
pub struct ClientError {
    pub request: Option<rpc_request::RpcRequest>,

    #[source]
    pub kind: ClientErrorKind,
}
</code>```

Below is how it's used in my code:

```<code>Err(err: ClientError) => {
  if let MyError(myError) = err.kind {
    ...
  }

  return Err(custom_error(err, ...));
}
</code>```

Which gives me the error:

```<code>use of partially moved value: `err`
partial move occurs because value has type `CustomType`, which does not implement the `Copy` trait
</code>```

How can I solve this partial move error? I have seen this SO answer: Struct with partial move errors. But suggests using &'static str which isn't valid for me & I don't want to use Rc<Mutex<..>> either.

Body:
I'm using a field of the struct ClientError (implemented in the Solana client):

#[derive(Error, Debug)]
#[error("{kind}")]
pub struct ClientError {
    pub request: Option<rpc_request::RpcRequest>,

    #[source]
    pub kind: ClientErrorKind,
}

Below is how it's used in my code:

Err(err: ClientError) => {
  if let MyError(myError) = err.kind {
    ...
  }

  return Err(custom_error(err, ...));
}

Which gives me the error:

use of partially moved value: `err`
partial move occurs because value has type `CustomType`, which does not implement the `Copy` trait

How can I solve this partial move error? I have seen this SO answer: Struct with partial move errors. But suggests using &'static str which isn't valid for me & I don't want to use Rc<Mutex<..>> either.


问:
Rootless Docker: Need to provide write access to a non-root user in docker container for a volume mounted on the host
I want to provide write access to a non-root user in a docker container for a volume mounted on the host. I have the same non-root user and group inside container and host as well.

While running the container, I mount a host volume to it -v /some/folder:/some/folder. I am doing this because my application running inside the docker container needs to write files to the mounted host folder. But since I am running my application as a non-root user, it doesn’t have permission to write to that folder.

Also, I this mounted folder permission is got changed inside the container automatically.
I have given assigned below user and group as an owner to this folder on the host:
“nonrootuser1:nonrootgroup1”

For 'rootful' docker it works fine, but if it's rootless inside the container it is showing below user and group as an owner to this folder:
“root:nobody”

Steps to reproduce this:

Add user and group on the host

```<code>groupadd -g 1015 nonrootgroup1
useradd -u 1099 nonrootuser1
</code>```

Create dir which will be assigned to osquery groupadd on the host:

```<code>sudo su

mkdir -p /var/osquery/sock
echo "hello world" > /var/osquery/sock/file.txt

chown root:nonrootgroup1 /var/osquery/sock
chmod g+s /var/osquery/sock/
</code>```

Create Dockerfile in the home directory :

```<code>FROM alpine:3.14

RUN addgroup -g 1015 -S nonrootgroup1
RUN adduser -D nonrootuser1 -u 1099

USER nonrootuser1:nonrootgroup1

CMD ["tail", "-f", "/dev/null"]
</code>```

Run docker container :

```<code>docker run --rm -d --name sample-app -v /var/osquery/sock:/var/osquery/sock $(docker build . -q)
</code>```

Check the user id of the container :

```<code>dmytro@dmytro:~/dev/sample-image$ docker exec sample-app id

uid=1099(nonrootuser1) gid=1015(nonrootgroup1) groups=1015(nonrootgroup1)
</code>```

check the permissions to the /var/osquery/sock dir inside the container :

Directory /var/osquery/sock is assigned to group 'nobody' instead of 'nonrootgroup1' group

```<code>dmytro@dmytro:~/dev/sample-image$ docker exec sample-app ls -lah /var/osquery
total 12K
drwxr-xr-x    3 root     root        4.0K Dec 28 10:47 .
drwxr-xr-x    1 root     root        4.0K Dec 28 10:47 ..
drwxr-s---    2 nobody   nobody      4.0K Dec 28 09:34 sock
</code>```

Host details are mentioned below:

```<code>Kernel Version: 5.4.0-135-generic
Operating System: Ubuntu 20.04.5 LTS
Storage Driver: overlay2
</code>```

Please suggest.

Thanks!

I tried to setup in the daemon.json "userns-remap" config, but docker daemon doesn't start with it, because it lacks permission to create dockremap user and group.

Body:
I want to provide write access to a non-root user in a docker container for a volume mounted on the host. I have the same non-root user and group inside container and host as well.

While running the container, I mount a host volume to it -v /some/folder:/some/folder. I am doing this because my application running inside the docker container needs to write files to the mounted host folder. But since I am running my application as a non-root user, it doesn’t have permission to write to that folder.

Also, I this mounted folder permission is got changed inside the container automatically.
I have given assigned below user and group as an owner to this folder on the host:
“nonrootuser1:nonrootgroup1”

For 'rootful' docker it works fine, but if it's rootless inside the container it is showing below user and group as an owner to this folder:
“root:nobody”

Steps to reproduce this:

Add user and group on the host

groupadd -g 1015 nonrootgroup1
useradd -u 1099 nonrootuser1

Create dir which will be assigned to osquery groupadd on the host:

sudo su

mkdir -p /var/osquery/sock
echo "hello world" > /var/osquery/sock/file.txt

chown root:nonrootgroup1 /var/osquery/sock
chmod g+s /var/osquery/sock/

Create Dockerfile in the home directory :

FROM alpine:3.14

RUN addgroup -g 1015 -S nonrootgroup1
RUN adduser -D nonrootuser1 -u 1099

USER nonrootuser1:nonrootgroup1

CMD ["tail", "-f", "/dev/null"]

Run docker container :

docker run --rm -d --name sample-app -v /var/osquery/sock:/var/osquery/sock $(docker build . -q)

Check the user id of the container :

dmytro@dmytro:~/dev/sample-image$ docker exec sample-app id

uid=1099(nonrootuser1) gid=1015(nonrootgroup1) groups=1015(nonrootgroup1)

check the permissions to the /var/osquery/sock dir inside the container :

Directory /var/osquery/sock is assigned to group 'nobody' instead of 'nonrootgroup1' group

dmytro@dmytro:~/dev/sample-image$ docker exec sample-app ls -lah /var/osquery
total 12K
drwxr-xr-x    3 root     root        4.0K Dec 28 10:47 .
drwxr-xr-x    1 root     root        4.0K Dec 28 10:47 ..
drwxr-s---    2 nobody   nobody      4.0K Dec 28 09:34 sock

Host details are mentioned below:

Kernel Version: 5.4.0-135-generic
Operating System: Ubuntu 20.04.5 LTS
Storage Driver: overlay2

Please suggest.

Thanks!

I tried to setup in the daemon.json "userns-remap" config, but docker daemon doesn't start with it, because it lacks permission to create dockremap user and group.


问:
Is there a way to use the timestamp function to draw a vertical line when the value no longer equals zero?

I'm trying to use the timestamp function to draw a vertical line when the value of my function no longer equals 0 using axvline. I have a function that varies from 0 to 1 named XV_tag, and I am trying to use axvline to draw a vertical line at the timestamp_x at the moment that XV_tag no longer equals 0.

Tried the following:

```<code>from matplotlib.ticker import MaxNLocator

#Find durations
start_i = 0
end_i = 1

# Conditions to be met variables
done_XV_loop = 0

while end_i < product_and_step_select_data.shape[0]:

    if (product_and_step_select_data["timestamp_x"][end_i] - product_and_step_select_data["timestamp_x"][start_i]).seconds > 60 or end_i == product_and_step_select_data.shape[0] - 1:

        fig = plt.figure(figsize=(11.69,8.27))
        plt.plot(product_and_step_select_data['timestamp_x'][start:end_i-1], product_and_step_select_data[XV_tag][start:end_i-1])

        if XV_tag != 0:
            plt.axvline(x = product_and_step_select_data['timestamp_x'][end_i-1], color = 'r', label = 'axvline - full height')

        else:
            plt.axvline(x = product_and_step_select_data['timestamp_x'][done_XV_loop], color = 'r', label = 'axvline - full height')
        plt.show()

    start_i = end_i
    end_i = end_i + 1
</code>```

Body:
I'm trying to use the timestamp function to draw a vertical line when the value of my function no longer equals 0 using axvline. I have a function that varies from 0 to 1 named XV_tag, and I am trying to use axvline to draw a vertical line at the timestamp_x at the moment that XV_tag no longer equals 0.

Tried the following:

from matplotlib.ticker import MaxNLocator

#Find durations
start_i = 0
end_i = 1

# Conditions to be met variables
done_XV_loop = 0

while end_i < product_and_step_select_data.shape[0]:

    if (product_and_step_select_data["timestamp_x"][end_i] - product_and_step_select_data["timestamp_x"][start_i]).seconds > 60 or end_i == product_and_step_select_data.shape[0] - 1:

        fig = plt.figure(figsize=(11.69,8.27))
        plt.plot(product_and_step_select_data['timestamp_x'][start:end_i-1], product_and_step_select_data[XV_tag][start:end_i-1])

        if XV_tag != 0:
            plt.axvline(x = product_and_step_select_data['timestamp_x'][end_i-1], color = 'r', label = 'axvline - full height')

        else:
            plt.axvline(x = product_and_step_select_data['timestamp_x'][done_XV_loop], color = 'r', label = 'axvline - full height')
        plt.show()

    start_i = end_i
    end_i = end_i + 1


问:
Custom function unable to detect i the value in VBA
I am creating a function which will allow me to return the row number. The user will give a matrix form range and a value. The function should bring back the row number. But the problem is that ith iteration thing is not working.

for example

```<code>FINDROW(some range from excel selection, 4) = 4
FINDROW(some range from excel selection, 7) = 7
</code>```

It just returns back the value that I give. Any idea why?

```<code>Function FINDROW(MAT As range, value)
Dim i As Integer

i = 1
For Each valu In MAT
        If valu = value Then
            If (i Mod 10) = 0 Then
                FINDROW = 10
                Exit Function
            Else
                FINDROW = i Mod 10
                Exit Function
            End If
        End If
i = i + 1
Next valu

FINDROW = "Not Found"
End Function

</code>```

If i give FINDROW = "hello" then it brings back "hello". So one thing is for sure that FINDROW is working. I just want it to return the mod of i or rather row number

Body:
I am creating a function which will allow me to return the row number. The user will give a matrix form range and a value. The function should bring back the row number. But the problem is that ith iteration thing is not working.

for example

FINDROW(some range from excel selection, 4) = 4
FINDROW(some range from excel selection, 7) = 7

It just returns back the value that I give. Any idea why?

Function FINDROW(MAT As range, value)
Dim i As Integer

i = 1
For Each valu In MAT
        If valu = value Then
            If (i Mod 10) = 0 Then
                FINDROW = 10
                Exit Function
            Else
                FINDROW = i Mod 10
                Exit Function
            End If
        End If
i = i + 1
Next valu

FINDROW = "Not Found"
End Function

If i give FINDROW = "hello" then it brings back "hello". So one thing is for sure that FINDROW is working. I just want it to return the mod of i or rather row number


问:
Save the changes that a user made
So, I used a code that creates a VBA calendar in Excel and it works fine. But the problem is: I want to mark certain days of the calendar but it does not save my changes. For example, if a make a change on 1/1/2023, go to another month and comeback to 1/1/2023 the change that I made is gone. What can i do to me the change permanent?

My code is:

```<code>Sub CalendarMaker()

       ' Unprotect sheet if had previous calendar to prevent error.
       ActiveSheet.Protect DrawingObjects:=False, Contents:=False, _
          Scenarios:=False
       ' Prevent screen flashing while drawing calendar.
       Application.ScreenUpdating = False
       ' Set up error trapping.
       On Error GoTo MyErrorTrap
       ' Clear area a1:g14 including any previous calendar.
       Range("a1:g14").Clear
       ' Use InputBox to get desired month and year and set variable
       ' MyInput.
       MyInput = InputBox("Type in Month and year for Calendar ")
       ' Allow user to end macro with Cancel in InputBox.
       If MyInput = "" Then Exit Sub
       ' Get the date value of the beginning of inputted month.
       StartDay = DateValue(MyInput)
       ' Check if valid date but not the first of the month
       ' -- if so, reset StartDay to first day of month.
       If Day(StartDay) <> 1 Then
           StartDay = DateValue(Month(StartDay) & "/1/" & _
               Year(StartDay))
       End If
       ' Prepare cell for Month and Year as fully spelled out.
       Range("a1").NumberFormat = "mmmm yyyy"
       ' Center the Month and Year label across a1:g1 with appropriate
       ' size, height and bolding.
       With Range("a1:g1")
           .HorizontalAlignment = xlCenterAcrossSelection
           .VerticalAlignment = xlCenter
           .Font.Size = 18
           .Font.Bold = True
           .RowHeight = 35
       End With
       ' Prepare a2:g2 for day of week labels with centering, size,
       ' height and bolding.
       With Range("a2:g2")
           .ColumnWidth = 11
           .VerticalAlignment = xlCenter
           .HorizontalAlignment = xlCenter
           .VerticalAlignment = xlCenter
           .Orientation = xlHorizontal
           .Font.Size = 12
           .Font.Bold = True
           .RowHeight = 20
       End With
       ' Put days of week in a2:g2.
       Range("a2") = "Sunday"
       Range("b2") = "Monday"
       Range("c2") = "Tuesday"
       Range("d2") = "Wednesday"
       Range("e2") = "Thursday"
       Range("f2") = "Friday"
       Range("g2") = "Saturday"
       ' Prepare a3:g7 for dates with left/top alignment, size, height
       ' and bolding.
       With Range("a3:g8")
           .HorizontalAlignment = xlRight
           .VerticalAlignment = xlTop
           .Font.Size = 18
           .Font.Bold = True
           .RowHeight = 21
       End With
       ' Put inputted month and year fully spelling out into "a1".
       Range("a1").Value = Application.Text(MyInput, "mmmm yyyy")
       ' Set variable and get which day of the week the month starts.
       DayofWeek = WeekDay(StartDay)
       ' Set variables to identify the year and month as separate
       ' variables.
       CurYear = Year(StartDay)
       CurMonth = Month(StartDay)
       ' Set variable and calculate the first day of the next month.
       FinalDay = DateSerial(CurYear, CurMonth + 1, 1)
       ' Place a "1" in cell position of the first day of the chosen
       ' month based on DayofWeek.
       Select Case DayofWeek
           Case 1
               Range("a3").Value = 1
           Case 2
               Range("b3").Value = 1
           Case 3
               Range("c3").Value = 1
           Case 4
               Range("d3").Value = 1
           Case 5
               Range("e3").Value = 1
           Case 6
               Range("f3").Value = 1
           Case 7
               Range("g3").Value = 1
       End Select
       ' Loop through range a3:g8 incrementing each cell after the "1"
       ' cell.
       For Each cell In Range("a3:g8")
           RowCell = cell.Row
           ColCell = cell.Column
           ' Do if "1" is in first column.
           If cell.Column = 1 And cell.Row = 3 Then
           ' Do if current cell is not in 1st column.
           ElseIf cell.Column <> 1 Then
               If cell.Offset(0, -1).Value >= 1 Then
                   cell.Value = cell.Offset(0, -1).Value + 1
                   ' Stop when the last day of the month has been
                   ' entered.
                   If cell.Value > (FinalDay - StartDay) Then
                       cell.Value = ""
                       ' Exit loop when calendar has correct number of
                       ' days shown.
                       Exit For
                   End If
               End If
           ' Do only if current cell is not in Row 3 and is in Column 1.
           ElseIf cell.Row > 3 And cell.Column = 1 Then
               cell.Value = cell.Offset(-1, 6).Value + 1
               ' Stop when the last day of the month has been entered.
               If cell.Value > (FinalDay - StartDay) Then
                   cell.Value = ""
                   ' Exit loop when calendar has correct number of days
                   ' shown.
                   Exit For
               End If
           End If
       Next

       ' Create Entry cells, format them centered, wrap text, and border
       ' around days.
       For x = 0 To 5
           Range("A4").Offset(x * 2, 0).EntireRow.Insert
           With Range("A4:G4").Offset(x * 2, 0)
               .RowHeight = 65
               .HorizontalAlignment = xlCenter
               .VerticalAlignment = xlTop
               .WrapText = True
               .Font.Size = 10
               .Font.Bold = False
               ' Unlock these cells to be able to enter text later after
               ' sheet is protected.
               .Locked = False
           End With
           ' Put border around the block of dates.
           With Range("A3").Offset(x * 2, 0).Resize(2, _
           7).Borders(xlLeft)
               .Weight = xlThick
               .ColorIndex = xlAutomatic
           End With

           With Range("A3").Offset(x * 2, 0).Resize(2, _
           7).Borders(xlRight)
               .Weight = xlThick
               .ColorIndex = xlAutomatic
           End With
           Range("A3").Offset(x * 2, 0).Resize(2, 7).BorderAround _
              Weight:=xlThick, ColorIndex:=xlAutomatic
       Next
       If Range("A13").Value = "" Then Range("A13").Offset(0, 0) _
          .Resize(2, 8).EntireRow.Delete
       ' Turn off gridlines.
       ActiveWindow.DisplayGridlines = False
       ' Protect sheet to prevent overwriting the dates.
       ActiveSheet.Protect DrawingObjects:=True, Contents:=True, _
          Scenarios:=True

       ' Resize window to show all of calendar (may have to be adjusted
       ' for video configuration).
       ActiveWindow.WindowState = xlMaximized
       ActiveWindow.ScrollRow = 1

       ' Allow screen to redraw with calendar showing.
       Application.ScreenUpdating = True
       ' Prevent going to error trap unless error found by exiting Sub
       ' here.
       Exit Sub
   ' Error causes msgbox to indicate the problem, provides new input box,
   ' and resumes at the line that caused the error.
   MyErrorTrap:
       MsgBox "You may not have entered your Month and Year correctly." _
           & Chr(13) & "Spell the Month correctly" _
           & " (or use 3 letter abbreviation)" _
           & Chr(13) & "and 4 digits for the Year"
       MyInput = InputBox("Type in Month and year for Calendar")
       If MyInput = "" Then Exit Sub
       Resume
   End Sub
</code>```

I expected to have a vba calendar where i can make changes on the dates i want

Title: Save the changes that a user made

Body:
So, I used a code that creates a VBA calendar in Excel and it works fine. But the problem is: I want to mark certain days of the calendar but it does not save my changes. For example, if a make a change on 1/1/2023, go to another month and comeback to 1/1/2023 the change that I made is gone. What can i do to me the change permanent?

My code is:

Sub CalendarMaker()

       ' Unprotect sheet if had previous calendar to prevent error.
       ActiveSheet.Protect DrawingObjects:=False, Contents:=False, _
          Scenarios:=False
       ' Prevent screen flashing while drawing calendar.
       Application.ScreenUpdating = False
       ' Set up error trapping.
       On Error GoTo MyErrorTrap
       ' Clear area a1:g14 including any previous calendar.
       Range("a1:g14").Clear
       ' Use InputBox to get desired month and year and set variable
       ' MyInput.
       MyInput = InputBox("Type in Month and year for Calendar ")
       ' Allow user to end macro with Cancel in InputBox.
       If MyInput = "" Then Exit Sub
       ' Get the date value of the beginning of inputted month.
       StartDay = DateValue(MyInput)
       ' Check if valid date but not the first of the month
       ' -- if so, reset StartDay to first day of month.
       If Day(StartDay) <> 1 Then
           StartDay = DateValue(Month(StartDay) & "/1/" & _
               Year(StartDay))
       End If
       ' Prepare cell for Month and Year as fully spelled out.
       Range("a1").NumberFormat = "mmmm yyyy"
       ' Center the Month and Year label across a1:g1 with appropriate
       ' size, height and bolding.
       With Range("a1:g1")
           .HorizontalAlignment = xlCenterAcrossSelection
           .VerticalAlignment = xlCenter
           .Font.Size = 18
           .Font.Bold = True
           .RowHeight = 35
       End With
       ' Prepare a2:g2 for day of week labels with centering, size,
       ' height and bolding.
       With Range("a2:g2")
           .ColumnWidth = 11
           .VerticalAlignment = xlCenter
           .HorizontalAlignment = xlCenter
           .VerticalAlignment = xlCenter
           .Orientation = xlHorizontal
           .Font.Size = 12
           .Font.Bold = True
           .RowHeight = 20
       End With
       ' Put days of week in a2:g2.
       Range("a2") = "Sunday"
       Range("b2") = "Monday"
       Range("c2") = "Tuesday"
       Range("d2") = "Wednesday"
       Range("e2") = "Thursday"
       Range("f2") = "Friday"
       Range("g2") = "Saturday"
       ' Prepare a3:g7 for dates with left/top alignment, size, height
       ' and bolding.
       With Range("a3:g8")
           .HorizontalAlignment = xlRight
           .VerticalAlignment = xlTop
           .Font.Size = 18
           .Font.Bold = True
           .RowHeight = 21
       End With
       ' Put inputted month and year fully spelling out into "a1".
       Range("a1").Value = Application.Text(MyInput, "mmmm yyyy")
       ' Set variable and get which day of the week the month starts.
       DayofWeek = WeekDay(StartDay)
       ' Set variables to identify the year and month as separate
       ' variables.
       CurYear = Year(StartDay)
       CurMonth = Month(StartDay)
       ' Set variable and calculate the first day of the next month.
       FinalDay = DateSerial(CurYear, CurMonth + 1, 1)
       ' Place a "1" in cell position of the first day of the chosen
       ' month based on DayofWeek.
       Select Case DayofWeek
           Case 1
               Range("a3").Value = 1
           Case 2
               Range("b3").Value = 1
           Case 3
               Range("c3").Value = 1
           Case 4
               Range("d3").Value = 1
           Case 5
               Range("e3").Value = 1
           Case 6
               Range("f3").Value = 1
           Case 7
               Range("g3").Value = 1
       End Select
       ' Loop through range a3:g8 incrementing each cell after the "1"
       ' cell.
       For Each cell In Range("a3:g8")
           RowCell = cell.Row
           ColCell = cell.Column
           ' Do if "1" is in first column.
           If cell.Column = 1 And cell.Row = 3 Then
           ' Do if current cell is not in 1st column.
           ElseIf cell.Column <> 1 Then
               If cell.Offset(0, -1).Value >= 1 Then
                   cell.Value = cell.Offset(0, -1).Value + 1
                   ' Stop when the last day of the month has been
                   ' entered.
                   If cell.Value > (FinalDay - StartDay) Then
                       cell.Value = ""
                       ' Exit loop when calendar has correct number of
                       ' days shown.
                       Exit For
                   End If
               End If
           ' Do only if current cell is not in Row 3 and is in Column 1.
           ElseIf cell.Row > 3 And cell.Column = 1 Then
               cell.Value = cell.Offset(-1, 6).Value + 1
               ' Stop when the last day of the month has been entered.
               If cell.Value > (FinalDay - StartDay) Then
                   cell.Value = ""
                   ' Exit loop when calendar has correct number of days
                   ' shown.
                   Exit For
               End If
           End If
       Next

       ' Create Entry cells, format them centered, wrap text, and border
       ' around days.
       For x = 0 To 5
           Range("A4").Offset(x * 2, 0).EntireRow.Insert
           With Range("A4:G4").Offset(x * 2, 0)
               .RowHeight = 65
               .HorizontalAlignment = xlCenter
               .VerticalAlignment = xlTop
               .WrapText = True
               .Font.Size = 10
               .Font.Bold = False
               ' Unlock these cells to be able to enter text later after
               ' sheet is protected.
               .Locked = False
           End With
           ' Put border around the block of dates.
           With Range("A3").Offset(x * 2, 0).Resize(2, _
           7).Borders(xlLeft)
               .Weight = xlThick
               .ColorIndex = xlAutomatic
           End With

           With Range("A3").Offset(x * 2, 0).Resize(2, _
           7).Borders(xlRight)
               .Weight = xlThick
               .ColorIndex = xlAutomatic
           End With
           Range("A3").Offset(x * 2, 0).Resize(2, 7).BorderAround _
              Weight:=xlThick, ColorIndex:=xlAutomatic
       Next
       If Range("A13").Value = "" Then Range("A13").Offset(0, 0) _
          .Resize(2, 8).EntireRow.Delete
       ' Turn off gridlines.
       ActiveWindow.DisplayGridlines = False
       ' Protect sheet to prevent overwriting the dates.
       ActiveSheet.Protect DrawingObjects:=True, Contents:=True, _
          Scenarios:=True

       ' Resize window to show all of calendar (may have to be adjusted
       ' for video configuration).
       ActiveWindow.WindowState = xlMaximized
       ActiveWindow.ScrollRow = 1

       ' Allow screen to redraw with calendar showing.
       Application.ScreenUpdating = True
       ' Prevent going to error trap unless error found by exiting Sub
       ' here.
       Exit Sub
   ' Error causes msgbox to indicate the problem, provides new input box,
   ' and resumes at the line that caused the error.
   MyErrorTrap:
       MsgBox "You may not have entered your Month and Year correctly." _
           & Chr(13) & "Spell the Month correctly" _
           & " (or use 3 letter abbreviation)" _
           & Chr(13) & "and 4 digits for the Year"
       MyInput = InputBox("Type in Month and year for Calendar")
       If MyInput = "" Then Exit Sub
       Resume
   End Sub

I expected to have a vba calendar where i can make changes on the dates i want


问:
Execute javascript code only after ajax request is complete
I am pretty new to php & Wordpress with a basic knowledge of html/css/js.
I have a php function in my functions.php that gets me the image url's and image titles of my websites media library and puts them in arrays.

Then, through Ajax, I receive these arrays to use in javascript. Like so:

```<code>const wp_image_url = [];
const wp_image_id = [];

$.ajax({
    url: '/wp-admin/admin-ajax.php',
    type: 'post',
    data: {
        action: 'mv_get_images_id',
    },
    dataType: "json",
    success: function(data) {
        for (let i = 0; i < data.length; i++) {
            wp_image_id.push(data[i]);
        }
        console.log(wp_image_id);
    },
    fail: function() {
        console.log('failed to load image data');
    },
});
$.ajax({
    url: '/wp-admin/admin-ajax.php',
    type: 'post',
    data: {
        action: 'mv_get_images_url',
    },
    dataType: "json",
    success: function(data) {
        for (let i = 0; i < data.length; i++) {
            wp_image_url.push(data[i]);
        }
        console.log(wp_image_url);
    },
    fail: function() {
        console.log('failed to load image data');
    },
});
console.log('these are below' + wp_image_id);
console.log('these are below' + wp_image_url);
console.log('init.js end');
</code>```

I then want to use the wp_image_id and wp_image_url variables in a later items.js script to generate div's with images in them based on the image url and titles based on the id. Like a Masonry gallery.

However, when I look at the network tab in my browser I see that the ajax request takes longer to happen causing the other js files to execute before the array's are filled with the necessary information.

the console when loading the site

I wonder if I can make it so the rest of the javascript only begins to run after the ajax requests are complete. I'm also kind of wondering if i'm going the right way in general.

To summarize I essentially want to get the image information of all my images in my wp media library, to then use this info to generate a masonry grid layout of images.

Body:
I am pretty new to php & Wordpress with a basic knowledge of html/css/js.
I have a php function in my functions.php that gets me the image url's and image titles of my websites media library and puts them in arrays.

Then, through Ajax, I receive these arrays to use in javascript. Like so:

const wp_image_url = [];
const wp_image_id = [];

$.ajax({
    url: '/wp-admin/admin-ajax.php',
    type: 'post',
    data: {
        action: 'mv_get_images_id',
    },
    dataType: "json",
    success: function(data) {
        for (let i = 0; i < data.length; i++) {
            wp_image_id.push(data[i]);
        }
        console.log(wp_image_id);
    },
    fail: function() {
        console.log('failed to load image data');
    },
});
$.ajax({
    url: '/wp-admin/admin-ajax.php',
    type: 'post',
    data: {
        action: 'mv_get_images_url',
    },
    dataType: "json",
    success: function(data) {
        for (let i = 0; i < data.length; i++) {
            wp_image_url.push(data[i]);
        }
        console.log(wp_image_url);
    },
    fail: function() {
        console.log('failed to load image data');
    },
});
console.log('these are below' + wp_image_id);
console.log('these are below' + wp_image_url);
console.log('init.js end');

I then want to use the wp_image_id and wp_image_url variables in a later items.js script to generate div's with images in them based on the image url and titles based on the id. Like a Masonry gallery.

However, when I look at the network tab in my browser I see that the ajax request takes longer to happen causing the other js files to execute before the array's are filled with the necessary information.

the console when loading the site

I wonder if I can make it so the rest of the javascript only begins to run after the ajax requests are complete. I'm also kind of wondering if i'm going the right way in general.

To summarize I essentially want to get the image information of all my images in my wp media library, to then use this info to generate a masonry grid layout of images.


问:
Problem with flicking transitions in BarbaJS
I have two problems with BarbaJS library.

The first one is a flickering animation when moving between pages and also sometimes the animation does not start. My lead is position: fixed on my header element. The animations look better but still don't fix the problem and I'd like to stay with position fixed on the header :D

Another problem is that the scripts from the previous page are adding to the next page. As you move between pages, scripts from the previous page are added to the new page.

You can find my website here https://melon.studio

I put data-barba="wrapper" into another div not  to exclude scripts from it. I tried to use position:relative but it doesnt help me ;/

Does anyone had problems like this?

I have very simply code for barbaJS

```<code>// BarbaJS scripts
barba.use(barbaCss);

barba.init({
  transitions: [
{
    // Slide from home to project
      name: 'cover',
      namespace: ['home', 'project', 'success'],
      enter(){},
      leave(){}
    }
  ]
});

barba.hooks.beforeEnter(() => {
  document.body.scrollTop = 0;
  intersectionObservers();
  magneticFunction();
  sliderHook();
});
</code>```

My CSS style for transitions

```<code>.transition {
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background-color: var(--clr-neutral-900);
    display: flex;
    align-items: center;
    justify-content: center;
    transform: translateY(-100%);
    z-index: 1;
}

.cover-leave-active,
.cover-enter-active,
.cover-leave-active .transition,
.cover-enter-active .transition {
    transition: transform 1s cubic-bezier(0.7, 0, 0.3, 1);
}

.cover-leave .transition {
    transform: translateY(-100%);
}

.cover-leave-to .transition {
    transform: translateY(0);
}

.cover-enter .transition {
    transform: translateY(0);
}

.cover-enter-to .transition {
    transform: translateY(100%);
}
</code>```

Body:
I have two problems with BarbaJS library.

The first one is a flickering animation when moving between pages and also sometimes the animation does not start. My lead is position: fixed on my header element. The animations look better but still don't fix the problem and I'd like to stay with position fixed on the header :D

Another problem is that the scripts from the previous page are adding to the next page. As you move between pages, scripts from the previous page are added to the new page.

You can find my website here https://melon.studio

I put data-barba="wrapper" into another div not  to exclude scripts from it. I tried to use position:relative but it doesnt help me ;/

Does anyone had problems like this?

I have very simply code for barbaJS

// BarbaJS scripts
barba.use(barbaCss);

barba.init({
  transitions: [
{
    // Slide from home to project
      name: 'cover',
      namespace: ['home', 'project', 'success'],
      enter(){},
      leave(){}
    }
  ]
});

barba.hooks.beforeEnter(() => {
  document.body.scrollTop = 0;
  intersectionObservers();
  magneticFunction();
  sliderHook();
});

My CSS style for transitions

.transition {
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background-color: var(--clr-neutral-900);
    display: flex;
    align-items: center;
    justify-content: center;
    transform: translateY(-100%);
    z-index: 1;
}

.cover-leave-active,
.cover-enter-active,
.cover-leave-active .transition,
.cover-enter-active .transition {
    transition: transform 1s cubic-bezier(0.7, 0, 0.3, 1);
}

.cover-leave .transition {
    transform: translateY(-100%);
}

.cover-leave-to .transition {
    transform: translateY(0);
}

.cover-enter .transition {
    transform: translateY(0);
}

.cover-enter-to .transition {
    transform: translateY(100%);
}


问:
Type for an Object-Array with a "Pick one of each" rule in io-ts
I'd like to define a type for an array using io-ts.

These are the possible values for the array

{ platform: 'A', metric: null }
{ platform: 'B', metric: 'A' }
{ platform: 'B', metric: 'B' }
{ platform: 'B', metric: 'C' }
```
<p>The crux is you should only be able to add one item per <code>platform</code> to the array and I have absolutely no clue how you would do that.</p>
<p>Here is what I have right now</p>
```import * as t from 'io-ts'

export const MyType = t.type({
  // ...other stuff

  metrics: t.array(t.union([
    t.type({ platform: t.literal('A'), metric: t.nullType }),
    t.type({ platform: t.literal('B'), metric: t.literal('A') }),
    t.type({ platform: t.literal('B'), metric: t.literal('B') }),
    t.type({ platform: t.literal('B'), metric: t.literal('C') })
  ]))
})

export type MyType = t.TypeOf<typeof MyType>
```
<p>And some examples of valid/invalid options</p>
```const var1: MyType = [{ platform: 'A', metric: null }] // Valid
const var2: MyType = [{ platform: 'B', metric: 'A' }] // Valid
const var3: MyType = [{ platform: 'A', metric: null }, { platform: 'B', metric: 'A' }] // Valid
const var4: MyType = [{ platform: 'B', metric: 'A' }, { platform: 'B', metric: 'B' }] // Invalid
```

I was thinking about splitting metrics into two seperate types (one for each platform) but I have no clue if there is a way to specify that you should only be able to add one of each possible values per platform. I did I bunch of googling but I'm not sure what exactly I am looking for. Could anyone point me into the right direction?

Body:
I'd like to define a type for an array using io-ts.

These are the possible values for the array

{ platform: 'A', metric: null }
{ platform: 'B', metric: 'A' }
{ platform: 'B', metric: 'B' }
{ platform: 'B', metric: 'C' }

The crux is you should only be able to add one item per platform to the array and I have absolutely no clue how you would do that.

Here is what I have right now

import * as t from 'io-ts'

export const MyType = t.type({
  // ...other stuff

  metrics: t.array(t.union([
    t.type({ platform: t.literal('A'), metric: t.nullType }),
    t.type({ platform: t.literal('B'), metric: t.literal('A') }),
    t.type({ platform: t.literal('B'), metric: t.literal('B') }),
    t.type({ platform: t.literal('B'), metric: t.literal('C') })
  ]))
})

export type MyType = t.TypeOf<typeof MyType>

And some examples of valid/invalid options

const var1: MyType = [{ platform: 'A', metric: null }] // Valid
const var2: MyType = [{ platform: 'B', metric: 'A' }] // Valid
const var3: MyType = [{ platform: 'A', metric: null }, { platform: 'B', metric: 'A' }] // Valid
const var4: MyType = [{ platform: 'B', metric: 'A' }, { platform: 'B', metric: 'B' }] // Invalid

I was thinking about splitting metrics into two seperate types (one for each platform) but I have no clue if there is a way to specify that you should only be able to add one of each possible values per platform. I did I bunch of googling but I'm not sure what exactly I am looking for. Could anyone point me into the right direction?


问:
How can i install apk within app without getting storage permissions
Now I can install the application without the play store with the apk that I downloaded from the server but i want to do this without asking for read/write permissions.

In Firebase app tester, we can install apk without obtaining read/write permissions. I want to do the same in my own application, but I couldn't find any working solution. I'm looking for a solution that will support api 19 and above.