问:
Unable to verify smart contract on polygoanMumbai using VSCode
I tried to verify my contract with constructor arguments but hardhat throwing that error everytime my smart contract file is given below
Domain.sol

```<code>    // SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.10;

// We first import some OpenZeppelin Contracts.
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/Counters.sol";

import {StringUtils} from "./libraries/StringUtils.sol";
// We import another help function
import {Base64} from "./libraries/Base64.sol";

import "hardhat/console.sol";

contract Domains is ERC721URIStorage {
    // Here's our domain TLD!

    // Magic given to us by OpenZeppelin to help us keep track of tokenIds.
    using Counters for Counters.Counter;
    Counters.Counter private _tokenIds;

    string public tld;

    // We'll be storing our NFT images on chain as SVGs
    string svgPartOne = '<svg xmlns="http://www.w3.org/2000/svg" width="270" height="270" fill="none"><path fill="url(#B)" d="M0 0h270v270H0z"/><defs><filter id="A" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse" height="270" width="270"><feDropShadow dx="0" dy="1" stdDeviation="2" flood-opacity=".225" width="200%" height="200%"/></filter></defs><path d="M 64.285156 52.769531 L 105.675781 122.433594 C 106.085938 123.125 106.828125 123.550781 107.632812 123.550781 C 108.433594 123.550781 109.175781 123.125 109.589844 122.433594 L 128.328125 90.894531 L 147.0625 122.433594 C 147.476562 123.125 148.21875 123.550781 149.023438 123.550781 C 149.824219 123.550781 150.566406 123.125 150.980469 122.433594 L 192.367188 52.769531 C 192.789062 52.058594 192.800781 51.179688 192.394531 50.457031 C 191.988281 49.742188 191.230469 49.296875 190.410156 49.296875 L 169.480469 49.296875 C 168.671875 49.296875 167.921875 49.730469 167.511719 50.429688 L 151.105469 78.582031 C 150.464844 79.671875 150.832031 81.078125 151.917969 81.71875 C 153.003906 82.359375 154.398438 81.996094 155.035156 80.902344 L 170.785156 53.886719 L 186.390625 53.886719 L 149.023438 116.78125 L 130.984375 86.421875 L 150.980469 52.769531 C 151.402344 52.058594 151.410156 51.179688 151.003906 50.457031 C 150.601562 49.742188 149.84375 49.296875 149.023438 49.296875 L 128.089844 49.296875 C 127.28125 49.296875 126.53125 49.730469 126.125 50.429688 L 109.714844 78.582031 C 109.078125 79.671875 109.441406 81.078125 110.527344 81.71875 C 111.613281 82.359375 113.011719 81.996094 113.648438 80.902344 L 129.398438 53.886719 L 145 53.886719 L 126.375 85.234375 C 126.371094 85.242188 126.363281 85.253906 126.359375 85.265625 L 107.632812 116.78125 L 70.261719 53.886719 L 103.796875 53.886719 L 99.210938 62.371094 C 98.609375 63.480469 99.015625 64.875 100.125 65.480469 C 101.230469 66.085938 102.613281 65.675781 103.214844 64.5625 L 109.636719 52.6875 C 110.019531 51.976562 110.003906 51.113281 109.59375 50.417969 C 109.179688 49.722656 108.4375 49.296875 107.632812 49.296875 L 66.242188 49.296875 C 65.421875 49.296875 64.664062 49.742188 64.257812 50.457031 C 63.855469 51.179688 63.863281 52.058594 64.285156 52.769531" fill="#A274FF"/><defs><linearGradient id="B" x1="0" y1="0" x2="270" y2="270" gradientUnits="userSpaceOnUse"><stop stop-color="#120037"/><stop offset="1" stop-color="#120037" stop-opacity=".99"/></linearGradient></defs><rect x="50" y="211" rx="20" ry="20" width="170" height="40" style="stroke:white; stroke-width:3 ;opacity:0.9"/><text x="50%" y="240" rx="20" ry="20" font-size="25" fill="#FFF" font-family="Plus Jakarta Sans,DejaVu Sans,Noto Color Emoji,Apple Color Emoji,sans-serif" font-weight="bold" text-anchor="middle">.Web3Shift</text><text x="50%" y="200" font-size="27" fill="#fff" filter="url(#A)" font-family="Plus Jakarta Sans,DejaVu Sans,Noto Color Emoji,Apple Color Emoji,sans-serif" font-weight="bold" text-anchor="middle">';
    string svgPartTwo = "</text></svg>";

    mapping(string => address) public domains;
    mapping(string => string) public records;

    address payable public owner;

    constructor(string memory _tld)
        payable
        ERC721("Web3Shift Name Service", "W3C")
    {
        owner = payable(msg.sender);
        tld = _tld;
        console.log("%s name service deployed", _tld);
    }

    function register(string calldata name) public payable {
        require(domains[name] == address(0));

        uint256 _price = price(name);
        require(msg.value >= _price, "Not enough Matic paid");

        // Combine the name passed into the function  with the TLD
        string memory _name = string(abi.encodePacked(name, ".", tld));

        string memory just_name = string(abi.encodePacked(name));
        // Create the SVG (image) for the NFT with the name
        string memory finalSvg = string(
            abi.encodePacked(svgPartOne, just_name, svgPartTwo)
        );
        uint256 newRecordId = _tokenIds.current();
        uint256 length = StringUtils.strlen(name);
        string memory strLen = Strings.toString(length);

        console.log(
            "Registering %s.%s on the contract with tokenID %d",
            name,
            tld,
            newRecordId
        );

        // Create the JSON metadata of our NFT. We do this by combining strings and encoding as base64
        string memory json = Base64.encode(
            abi.encodePacked(
                '{"name": "',
                _name,
                '", "description": "A domain on the Web3Shift name service", "image": "data:image/svg+xml;base64,',
                Base64.encode(bytes(finalSvg)),
                '","length":"',
                strLen,
                '"}'
            )
        );

        string memory finalTokenUri = string(
            abi.encodePacked("data:application/json;base64,", json)
        );

        console.log(
            "\n--------------------------------------------------------"
        );
        console.log("Final tokenURI", finalTokenUri);
        console.log(
            "--------------------------------------------------------\n"
        );

        _safeMint(msg.sender, newRecordId);
        _setTokenURI(newRecordId, finalTokenUri);
        domains[name] = msg.sender;

        _tokenIds.increment();
    }

    // This function will give us the price of a domain based on length
    function price(string calldata name) public pure returns (uint256) {
        uint256 len = StringUtils.strlen(name);
        require(len > 0);
        if (len == 1) {
            return 3 * 10**17; // 5 MATIC = 5 000 000 000 000 000 000 (18 decimals). We're going with 0.5 Matic cause the faucets don't give a lot
        } else if (len == 3) {
            return 2 * 10**17; // To charge smaller amounts, reduce the decimals. This is 0.3
        } else {
            return 1 * 10**17;
        }
    }

    // Other functions unchanged

    function getAddress(string calldata name) public view returns (address) {
        // Check that the owner is the transaction sender
        return domains[name];
    }

    function setRecord(string calldata name, string calldata record) public {
        // Check that the owner is the transaction sender
        require(domains[name] == msg.sender);
        records[name] = record;
    }

    function getRecord(string calldata name)
        public
        view
        returns (string memory)
    {
        return records[name];
    }

    modifier onlyOwner() {
        require(isOwner());
        _;
    }

    function isOwner() public view returns (bool) {
        return msg.sender == owner;
    }

    function withdraw() public onlyOwner {
        uint256 amount = address(this).balance;

        (bool success, ) = msg.sender.call{value: amount}("");
        require(success, "Failed to withdraw Matic");
    }
}
</code>```

hardhat.config.js

```<code>require("@nomiclabs/hardhat-waffle");
require("@nomiclabs/hardhat-etherscan");

const dotenv = require("dotenv");
dotenv.config();

//require("dotenv").config();

module.exports = {
    solidity: "0.8.10",
    etherscan: {
        apiKey: {
            goerli: "UGFT5V9QWSATQN8ERITGYZPT3VHN8EGZD3",
            polygonMumbai: "TIG8FUTP9DKH2KN4957JCWIDWQSPQNEFKN",
        }
    },
    networks: {
        mumbai: {
            url: process.env.url,
            accounts: [process.env.key],
        },
        goerli: {
            url: `https://eth-goerli.alchemyapi.io/v2/${ALCHEMY_API_KEY}`,
            accounts: [process.env.goerli],
        }
    },
    polygon: {
        apiKey: {
            polygonMumbai: "TIG8FUTP9DKH2KN4957JCWIDWQSPQNEFKN",
        }
    },
};
</code>```

npx hardhat verify --network mumbai 0xB775e8D2A925836E216EcDea9E23A72c4AbF222f

```<code>(node:25360) ExperimentalWarning: stream/web is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
Nothing to compile
Error in plugin @nomiclabs/hardhat-etherscan: The constructor for contracts/Domains.sol:Domains has 1 parameters
but 0 arguments were provided instead.
</code>```

When I pass the argument then

npx hardhat verify --network mumbai 0xB775e8D2A925836E216EcDea9E23A72c4AbF222f 1

```<code>(node:26960) ExperimentalWarning: stream/web is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
Nothing to compile
Successfully submitted source code for contract
contracts/Domains.sol:Domains at 0xB775e8D2A925836E216EcDea9E23A72c4AbF222f
for verification on the block explorer. Waiting for verification result...

We tried verifying your contract Domains without including any unrelated one, but it failed.
Trying again with the full solc input used to compile and deploy it.
This means that unrelated contracts may be displayed on Etherscan...

Successfully submitted source code for contract
contracts/Domains.sol:Domains at 0xB775e8D2A925836E216EcDea9E23A72c4AbF222f
for verification on the block explorer. Waiting for verification result...

Error in plugin @nomiclabs/hardhat-etherscan: The contract verification failed.
Reason: Fail - Unable to verify
</code>```

Body:
I tried to verify my contract with constructor arguments but hardhat throwing that error everytime my smart contract file is given below
Domain.sol

    // SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.10;

// We first import some OpenZeppelin Contracts.
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/Counters.sol";

import {StringUtils} from "./libraries/StringUtils.sol";
// We import another help function
import {Base64} from "./libraries/Base64.sol";

import "hardhat/console.sol";

contract Domains is ERC721URIStorage {
    // Here's our domain TLD!

    // Magic given to us by OpenZeppelin to help us keep track of tokenIds.
    using Counters for Counters.Counter;
    Counters.Counter private _tokenIds;

    string public tld;

    // We'll be storing our NFT images on chain as SVGs
    string svgPartOne = '<svg xmlns="http://www.w3.org/2000/svg" width="270" height="270" fill="none"><path fill="url(#B)" d="M0 0h270v270H0z"/><defs><filter id="A" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse" height="270" width="270"><feDropShadow dx="0" dy="1" stdDeviation="2" flood-opacity=".225" width="200%" height="200%"/></filter></defs><path d="M 64.285156 52.769531 L 105.675781 122.433594 C 106.085938 123.125 106.828125 123.550781 107.632812 123.550781 C 108.433594 123.550781 109.175781 123.125 109.589844 122.433594 L 128.328125 90.894531 L 147.0625 122.433594 C 147.476562 123.125 148.21875 123.550781 149.023438 123.550781 C 149.824219 123.550781 150.566406 123.125 150.980469 122.433594 L 192.367188 52.769531 C 192.789062 52.058594 192.800781 51.179688 192.394531 50.457031 C 191.988281 49.742188 191.230469 49.296875 190.410156 49.296875 L 169.480469 49.296875 C 168.671875 49.296875 167.921875 49.730469 167.511719 50.429688 L 151.105469 78.582031 C 150.464844 79.671875 150.832031 81.078125 151.917969 81.71875 C 153.003906 82.359375 154.398438 81.996094 155.035156 80.902344 L 170.785156 53.886719 L 186.390625 53.886719 L 149.023438 116.78125 L 130.984375 86.421875 L 150.980469 52.769531 C 151.402344 52.058594 151.410156 51.179688 151.003906 50.457031 C 150.601562 49.742188 149.84375 49.296875 149.023438 49.296875 L 128.089844 49.296875 C 127.28125 49.296875 126.53125 49.730469 126.125 50.429688 L 109.714844 78.582031 C 109.078125 79.671875 109.441406 81.078125 110.527344 81.71875 C 111.613281 82.359375 113.011719 81.996094 113.648438 80.902344 L 129.398438 53.886719 L 145 53.886719 L 126.375 85.234375 C 126.371094 85.242188 126.363281 85.253906 126.359375 85.265625 L 107.632812 116.78125 L 70.261719 53.886719 L 103.796875 53.886719 L 99.210938 62.371094 C 98.609375 63.480469 99.015625 64.875 100.125 65.480469 C 101.230469 66.085938 102.613281 65.675781 103.214844 64.5625 L 109.636719 52.6875 C 110.019531 51.976562 110.003906 51.113281 109.59375 50.417969 C 109.179688 49.722656 108.4375 49.296875 107.632812 49.296875 L 66.242188 49.296875 C 65.421875 49.296875 64.664062 49.742188 64.257812 50.457031 C 63.855469 51.179688 63.863281 52.058594 64.285156 52.769531" fill="#A274FF"/><defs><linearGradient id="B" x1="0" y1="0" x2="270" y2="270" gradientUnits="userSpaceOnUse"><stop stop-color="#120037"/><stop offset="1" stop-color="#120037" stop-opacity=".99"/></linearGradient></defs><rect x="50" y="211" rx="20" ry="20" width="170" height="40" style="stroke:white; stroke-width:3 ;opacity:0.9"/><text x="50%" y="240" rx="20" ry="20" font-size="25" fill="#FFF" font-family="Plus Jakarta Sans,DejaVu Sans,Noto Color Emoji,Apple Color Emoji,sans-serif" font-weight="bold" text-anchor="middle">.Web3Shift</text><text x="50%" y="200" font-size="27" fill="#fff" filter="url(#A)" font-family="Plus Jakarta Sans,DejaVu Sans,Noto Color Emoji,Apple Color Emoji,sans-serif" font-weight="bold" text-anchor="middle">';
    string svgPartTwo = "</text></svg>";

    mapping(string => address) public domains;
    mapping(string => string) public records;

    address payable public owner;

    constructor(string memory _tld)
        payable
        ERC721("Web3Shift Name Service", "W3C")
    {
        owner = payable(msg.sender);
        tld = _tld;
        console.log("%s name service deployed", _tld);
    }

    function register(string calldata name) public payable {
        require(domains[name] == address(0));

        uint256 _price = price(name);
        require(msg.value >= _price, "Not enough Matic paid");

        // Combine the name passed into the function  with the TLD
        string memory _name = string(abi.encodePacked(name, ".", tld));

        string memory just_name = string(abi.encodePacked(name));
        // Create the SVG (image) for the NFT with the name
        string memory finalSvg = string(
            abi.encodePacked(svgPartOne, just_name, svgPartTwo)
        );
        uint256 newRecordId = _tokenIds.current();
        uint256 length = StringUtils.strlen(name);
        string memory strLen = Strings.toString(length);

        console.log(
            "Registering %s.%s on the contract with tokenID %d",
            name,
            tld,
            newRecordId
        );

        // Create the JSON metadata of our NFT. We do this by combining strings and encoding as base64
        string memory json = Base64.encode(
            abi.encodePacked(
                '{"name": "',
                _name,
                '", "description": "A domain on the Web3Shift name service", "image": "data:image/svg+xml;base64,',
                Base64.encode(bytes(finalSvg)),
                '","length":"',
                strLen,
                '"}'
            )
        );

        string memory finalTokenUri = string(
            abi.encodePacked("data:application/json;base64,", json)
        );

        console.log(
            "\n--------------------------------------------------------"
        );
        console.log("Final tokenURI", finalTokenUri);
        console.log(
            "--------------------------------------------------------\n"
        );

        _safeMint(msg.sender, newRecordId);
        _setTokenURI(newRecordId, finalTokenUri);
        domains[name] = msg.sender;

        _tokenIds.increment();
    }

    // This function will give us the price of a domain based on length
    function price(string calldata name) public pure returns (uint256) {
        uint256 len = StringUtils.strlen(name);
        require(len > 0);
        if (len == 1) {
            return 3 * 10**17; // 5 MATIC = 5 000 000 000 000 000 000 (18 decimals). We're going with 0.5 Matic cause the faucets don't give a lot
        } else if (len == 3) {
            return 2 * 10**17; // To charge smaller amounts, reduce the decimals. This is 0.3
        } else {
            return 1 * 10**17;
        }
    }

    // Other functions unchanged

    function getAddress(string calldata name) public view returns (address) {
        // Check that the owner is the transaction sender
        return domains[name];
    }

    function setRecord(string calldata name, string calldata record) public {
        // Check that the owner is the transaction sender
        require(domains[name] == msg.sender);
        records[name] = record;
    }

    function getRecord(string calldata name)
        public
        view
        returns (string memory)
    {
        return records[name];
    }

    modifier onlyOwner() {
        require(isOwner());
        _;
    }

    function isOwner() public view returns (bool) {
        return msg.sender == owner;
    }

    function withdraw() public onlyOwner {
        uint256 amount = address(this).balance;

        (bool success, ) = msg.sender.call{value: amount}("");
        require(success, "Failed to withdraw Matic");
    }
}

hardhat.config.js

require("@nomiclabs/hardhat-waffle");
require("@nomiclabs/hardhat-etherscan");

const dotenv = require("dotenv");
dotenv.config();

//require("dotenv").config();

module.exports = {
    solidity: "0.8.10",
    etherscan: {
        apiKey: {
            goerli: "UGFT5V9QWSATQN8ERITGYZPT3VHN8EGZD3",
            polygonMumbai: "TIG8FUTP9DKH2KN4957JCWIDWQSPQNEFKN",
        }
    },
    networks: {
        mumbai: {
            url: process.env.url,
            accounts: [process.env.key],
        },
        goerli: {
            url: `https://eth-goerli.alchemyapi.io/v2/${ALCHEMY_API_KEY}`,
            accounts: [process.env.goerli],
        }
    },
    polygon: {
        apiKey: {
            polygonMumbai: "TIG8FUTP9DKH2KN4957JCWIDWQSPQNEFKN",
        }
    },
};

npx hardhat verify --network mumbai 0xB775e8D2A925836E216EcDea9E23A72c4AbF222f

(node:25360) ExperimentalWarning: stream/web is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
Nothing to compile
Error in plugin @nomiclabs/hardhat-etherscan: The constructor for contracts/Domains.sol:Domains has 1 parameters
but 0 arguments were provided instead.

When I pass the argument then

npx hardhat verify --network mumbai 0xB775e8D2A925836E216EcDea9E23A72c4AbF222f 1

(node:26960) ExperimentalWarning: stream/web is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
Nothing to compile
Successfully submitted source code for contract
contracts/Domains.sol:Domains at 0xB775e8D2A925836E216EcDea9E23A72c4AbF222f
for verification on the block explorer. Waiting for verification result...

We tried verifying your contract Domains without including any unrelated one, but it failed.
Trying again with the full solc input used to compile and deploy it.
This means that unrelated contracts may be displayed on Etherscan...

Successfully submitted source code for contract
contracts/Domains.sol:Domains at 0xB775e8D2A925836E216EcDea9E23A72c4AbF222f
for verification on the block explorer. Waiting for verification result...

Error in plugin @nomiclabs/hardhat-etherscan: The contract verification failed.
Reason: Fail - Unable to verify


来源: stackexchange

问:
docker compose env_file with config file content
How do i represent the following environment variable in docker-compose.yaml file using env_file file

here is what works fine using the environments to represent the environment variable

```<code>    environment:
      AKHQ_CONFIGURATION: |
        akhq:
          connections:
            docker-kafka-server:
              properties:
                bootstrap.servers: "kafka:9092"

</code>```

using the env_file https://docs.docker.com/compose/environment-variables/#the-env_file-configuration-option

```<code>    env_file:
      - ./.env
</code>```

here is what i have as content for .env

```<code>AKHQ_CONFIGURATION: |
  akhq:
    connections:
      docker-kafka-server:
        properties:
          bootstrap.servers: "kafka:9092"
</code>```

but i am getting the following errors

```<code>unexpected character "-" in variable name near "docker-kafka-server:\n        properties:\n          bootstrap.servers: \"kafka:9092\"\n
</code>```

so what should be the proper format for the content of .env file?

ContentLicense: CC BY-SA 4.0

Body:
How do i represent the following environment variable in docker-compose.yaml file using env_file file

here is what works fine using the environments to represent the environment variable

    environment:
      AKHQ_CONFIGURATION: |
        akhq:
          connections:
            docker-kafka-server:
              properties:
                bootstrap.servers: "kafka:9092"

using the env_file https://docs.docker.com/compose/environment-variables/#the-env_file-configuration-option

    env_file:
      - ./.env

here is what i have as content for .env

AKHQ_CONFIGURATION: |
  akhq:
    connections:
      docker-kafka-server:
        properties:
          bootstrap.servers: "kafka:9092"

but i am getting the following errors

unexpected character "-" in variable name near "docker-kafka-server:\n        properties:\n          bootstrap.servers: \"kafka:9092\"\n

so what should be the proper format for the content of .env file?


问:
In mat-table I have drop-down menu In that DropDown menu after select specific option than only that menu have to disabled for specific row
[Html File](https://i.stack.imgur.com/xhoxC.png)
[Ts File](https://i.stack.imgur.com/2CAHX.png)

Output of mat-table
Here Selecting "Done" only I want Disabled Not For Other Options
And Disabled will be only for that perticular row

I tried with the above code and I get disabled all Select options of every row


问:
android upload photo using share intent error
i am trying to allow the user to upload photos via share intent.
but i get an exception:tag scaleimagetask.run  no content provider /mnt/sdcard/pic.png
do ineed to add something to the manifest or do something else?

my code:

```<code>{
    Intent sharingIntent = new Intent(Intent.ACTION_SEND);
    Uri phototUri = Uri.parse(path);
    sharingIntent.setData(photootUri);
    sharingIntent.setType("image/png");
    sharingIntent.putExtra(Intent.EXTRA_STREAM, photootUri);
    getContext().startActivity(Intent.createChooser(sharingIntent, "Share image using"));
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i am trying to allow the user to upload photos via share intent.
but i get an exception:tag scaleimagetask.run  no content provider /mnt/sdcard/pic.png
do ineed to add something to the manifest or do something else?

my code:

{
    Intent sharingIntent = new Intent(Intent.ACTION_SEND);
    Uri phototUri = Uri.parse(path);
    sharingIntent.setData(photootUri);
    sharingIntent.setType("image/png");
    sharingIntent.putExtra(Intent.EXTRA_STREAM, photootUri);
    getContext().startActivity(Intent.createChooser(sharingIntent, "Share image using"));
}


问:
Chrome headless executes test over 40 seconds
I have issue with running tests in headless mode with chrome options.

ChromeOptions options = new ChromeOptions(); options.addArguments("--headless");  driver = new ChromeDriver(options);

In UI mode test is executed fast(4seconds), but when I enable headless mode (40 seconds)

Headless mode:

UI mode:

Is there any other way to use chrome headless, whether something is changed in the mean time in driver itself? I have tried with different java, browser version and chrome driver and issue is the same..

Selenium 4.3.0, TestNG 7.4.0


问:
JsonElement convert hex or Base64 to byte array, problem with 0x00
Why string "0x00" is recognized as Base64 in convert method?
I'am trying convert JsonElement to byte[]. In JsonElement I have "0x00" but:

```<code>Span<byte> buffer = new Span<byte>(new byte[toConvert.Length]); // toConvert is JsonElement.ToString()
bool t = Convert.TryFromBase64String(toConvert, buffer, out int bytesParsed);
</code>```

and

```<code>jsonElement.TryGetBytesFromBase64(out byte[] returnBytes)
</code>```

Both method return true with

byte[211,29,52] - jsonElement.TryGetBytesFromBase64
byte[211,29,52,0] - Convert.TryFromBase64String

For "0x00" in byte[] should I have byte[0]. How can I fix it?

Body:
Why string "0x00" is recognized as Base64 in convert method?
I'am trying convert JsonElement to byte[]. In JsonElement I have "0x00" but:

Span<byte> buffer = new Span<byte>(new byte[toConvert.Length]); // toConvert is JsonElement.ToString()
bool t = Convert.TryFromBase64String(toConvert, buffer, out int bytesParsed);

and

jsonElement.TryGetBytesFromBase64(out byte[] returnBytes)

Both method return true with

byte[211,29,52] - jsonElement.TryGetBytesFromBase64
byte[211,29,52,0] - Convert.TryFromBase64String

For "0x00" in byte[] should I have byte[0]. How can I fix it?


问:
React custom responsiveness and position of modal dialogue on page load
Currently working on a React project, with styled-components. I am trying to make my modal responsive. Like when the page loads, the modal should be fixed just below the "add event" button.

Sadly, it is but when I change screen size, it does NOT move with that button or the page, and remains at that fixed position for different screens, like a normal modal does

Click to view Image

I have tried changing the margins and position, still no difference. The Modal remains as a fixed overlay and is not responsive with the page components.


问:
unrecognised selector sent to instance when attaching GLFW Cocoa Window to IPlugView (VST3SDK)
I'm doing some work with the Steinberg VST3SDK and have bumped into an error I don't really understand:

```<code>[GLFWWindow window]: unrecognized selector sent to instance 0x7fe10430a830
2022-12-22 08:11:08.981 MyHost[1593:20791] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[GLFWWindow window]: unrecognized selector sent to instance 0x7fe10430a830'
*** First throw call stack:
(
        0   CoreFoundation                      0x00007fff37903a17 __exceptionPreprocess + 250
        1   libobjc.A.dylib                     0x00007fff70468a9e objc_exception_throw + 48
        2   CoreFoundation                      0x00007fff37982e36 -[NSObject(NSObject) __retain_OA] + 0
        3   CoreFoundation                      0x00007fff37868190 ___forwarding___ + 1427
        4   CoreFoundation                      0x00007fff37867b68 _CF_forwarding_prep_0 + 120
        5   Digitalis                           0x000000010a9dc990 GetPluginFactory + 1922288
        6   Digitalis                           0x000000010a9dbb85 GetPluginFactory + 1918693
        7   Digitalis                           0x000000010a80db6e GetPluginFactory + 26318
        8   MyHost                              0x000000010a624641 _ZN6Plugin4loadERKNSt3__112basic_stringIcNS0_11char_traitsIcEENS0_9allocatorIcEEEE + 2065
        9   MyHost                              0x000000010a624e9d main + 61
        10  libdyld.dylib                       0x00007fff71608cc9 start + 1
        11  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
</code>```

i guess this leads me to question whether the kPlatformType “NSView” is equivalent to glfwGetCocoaWindow()'s “NSWindow” return value?
heres the snippet of code thats causing me errors:

```<code>  if (!glfwInit()) {
    std::cout << "Failed to initialise Editor Window" << std::endl;
    return false;
  }
  auto view = controller->createView(Steinberg::Vst::ViewType::kEditor);
  Steinberg::ViewRect dimensions;
  view->getSize(&dimensions);
  editorWindow = glfwCreateWindow(dimensions.getWidth(), dimensions.getHeight(), "VST 3 SDK", nullptr, nullptr);
  view->attached(glfwGetCocoaWindow(editorWindow), Steinberg::kPlatformTypeNSView);
</code>```

can also confirm that the windows equivalent of this works fine:

```<code>view->attached(glfwGetWin32Window(editorWindow), Steinberg::kPlatformTypeHWN
</code>```

any type of explanation whether it be for debugging the error message itself or the VST3SDK side would be greatly appreciated!

i tried:

```<code>  view->attached(glfwGetCocoaWindow(editorWindow), Steinberg::kPlatformTypeNSView);

</code>```

and expected the vst3 view to be attached to my GLFW window

Body:
I'm doing some work with the Steinberg VST3SDK and have bumped into an error I don't really understand:

[GLFWWindow window]: unrecognized selector sent to instance 0x7fe10430a830
2022-12-22 08:11:08.981 MyHost[1593:20791] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[GLFWWindow window]: unrecognized selector sent to instance 0x7fe10430a830'
*** First throw call stack:
(
        0   CoreFoundation                      0x00007fff37903a17 __exceptionPreprocess + 250
        1   libobjc.A.dylib                     0x00007fff70468a9e objc_exception_throw + 48
        2   CoreFoundation                      0x00007fff37982e36 -[NSObject(NSObject) __retain_OA] + 0
        3   CoreFoundation                      0x00007fff37868190 ___forwarding___ + 1427
        4   CoreFoundation                      0x00007fff37867b68 _CF_forwarding_prep_0 + 120
        5   Digitalis                           0x000000010a9dc990 GetPluginFactory + 1922288
        6   Digitalis                           0x000000010a9dbb85 GetPluginFactory + 1918693
        7   Digitalis                           0x000000010a80db6e GetPluginFactory + 26318
        8   MyHost                              0x000000010a624641 _ZN6Plugin4loadERKNSt3__112basic_stringIcNS0_11char_traitsIcEENS0_9allocatorIcEEEE + 2065
        9   MyHost                              0x000000010a624e9d main + 61
        10  libdyld.dylib                       0x00007fff71608cc9 start + 1
        11  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

i guess this leads me to question whether the kPlatformType “NSView” is equivalent to glfwGetCocoaWindow()'s “NSWindow” return value?
heres the snippet of code thats causing me errors:

  if (!glfwInit()) {
    std::cout << "Failed to initialise Editor Window" << std::endl;
    return false;
  }
  auto view = controller->createView(Steinberg::Vst::ViewType::kEditor);
  Steinberg::ViewRect dimensions;
  view->getSize(&dimensions);
  editorWindow = glfwCreateWindow(dimensions.getWidth(), dimensions.getHeight(), "VST 3 SDK", nullptr, nullptr);
  view->attached(glfwGetCocoaWindow(editorWindow), Steinberg::kPlatformTypeNSView);

can also confirm that the windows equivalent of this works fine:

view->attached(glfwGetWin32Window(editorWindow), Steinberg::kPlatformTypeHWN

any type of explanation whether it be for debugging the error message itself or the VST3SDK side would be greatly appreciated!

i tried:

  view->attached(glfwGetCocoaWindow(editorWindow), Steinberg::kPlatformTypeNSView);

and expected the vst3 view to be attached to my GLFW window


问:
Establish link to a part in another markdown file
I am trying to establish a link from one markdown file (a.md) to a part in another markdown file (b.md).
I tried \ref, \section etc...which did not work.

What finally worked is

In a.md
[@satisfies{123451}] (_expectations.html#123451)

and in b.md

\page Expectations Expectations Collection

--> ## 123451 appended with anchor a name ""

But, the generated html file by doxygen shows
satisfies 123451 \n

where is this \n coming from?
Is there a better way to establish the links?

Thanks in advance.


问:
Serilog custom sink with dependency Injection
I know there are several questions on this topic but haven't found anything working for me.
My problem seems to be that there is some kind of circular reference because I keep hitting the code in UseSerilog() over and over. I have tried to inject several different services but all get the same problem. In program.cs I have:

```<code>public static void Main()
{
    var host = new HostBuilder()
        .ConfigureAppConfiguration(config =>
        {
            var environmentName = Environment.GetEnvironmentVariable("AZURE_FUNCTIONS_ENVIRONMENT");
            if (environmentName.IsDevelopment())
            {
                config.AddJsonFile($"local.settings.json", optional: true, reloadOnChange: false);
            }
            config.AddEnvironmentVariables();
        })
        .UseSerilog((context, services, configuration) =>
        {
            configuration
                .ReadFrom.Configuration(context.Configuration)
                .ReadFrom.Services(services)
                .WriteTo.WintSink(services.GetRequiredService<IMyRequiredService>());
        })
        .ConfigureServices(ConfigureServices)
        .Build();
        host.Run();
}
</code>```

Update 1:

I have managed to get it working if I use the Serilog.ILogger interface instead of Microsoft.Extensions.Logging.ILogger (not what I wanted) in combination with:

```<code>            services.AddSingleton<Serilog.ILogger>(sp =>
        {
            var service = sp.GetRequiredService<IMyRequiredService>();

            return new LoggerConfiguration()
                .MinimumLevel.Debug()
                .WriteTo.WintSink(service)
                .CreateLogger();
        });

        services.AddLogging(configure => configure.ClearProviders().AddSerilog());
</code>```

Body:
I know there are several questions on this topic but haven't found anything working for me.
My problem seems to be that there is some kind of circular reference because I keep hitting the code in UseSerilog() over and over. I have tried to inject several different services but all get the same problem. In program.cs I have:

public static void Main()
{
    var host = new HostBuilder()
        .ConfigureAppConfiguration(config =>
        {
            var environmentName = Environment.GetEnvironmentVariable("AZURE_FUNCTIONS_ENVIRONMENT");
            if (environmentName.IsDevelopment())
            {
                config.AddJsonFile($"local.settings.json", optional: true, reloadOnChange: false);
            }
            config.AddEnvironmentVariables();
        })
        .UseSerilog((context, services, configuration) =>
        {
            configuration
                .ReadFrom.Configuration(context.Configuration)
                .ReadFrom.Services(services)
                .WriteTo.WintSink(services.GetRequiredService<IMyRequiredService>());
        })
        .ConfigureServices(ConfigureServices)
        .Build();
        host.Run();
}

Update 1:

I have managed to get it working if I use the Serilog.ILogger interface instead of Microsoft.Extensions.Logging.ILogger (not what I wanted) in combination with:

            services.AddSingleton<Serilog.ILogger>(sp =>
        {
            var service = sp.GetRequiredService<IMyRequiredService>();

            return new LoggerConfiguration()
                .MinimumLevel.Debug()
                .WriteTo.WintSink(service)
                .CreateLogger();
        });

        services.AddLogging(configure => configure.ClearProviders().AddSerilog());


问:
Loop through Multidimensional array and update mysql table using codeignitor 3
I am trying to loop through multidimensional array to update the values in mysql table in codeignitor 3

I have an issue in looping through the values in multidimensional array

Below is my Multidimensional array:

$data = array(
    'invoice_id' => $invoice_id,
    'date' => $this->input->post('date',true),
    'commercial_invoice_number' => $this->input->post('commercial_invoice_number',true),
    'payment_type' => $this->input->post('payment_type',true)
);
```
<p>When printing this array ,$data contains as below</p>
```(
    [invoice_id] => Array
        (
            [0] => 4549344712
            [1] => 4549344713
            [2] => 4549344814
        )
    [date] => Array
        (
            [0] => 25-11-2022
            [1] => 22-12-2022
            [2] => 12-10-2022
        )
    [commercial_invoice_number] => Array
        (
            [0] => NS202211-4
            [1] => NS202211-5
            [2] => NS202211-6
        )
    [payment_type] => Array
        (
            [0] => 0
            [1] => 1
            [2] => 0
        )
        )
```
<p>print_r($invoice_id) returns as below</p>
<p><code>Array ( [0] => 4549344712 [1] => 4549344713 [2] => 4549344814 )</code></p>
<pre class="lang-php prettyprint-override"><code>foreach ($invoice_id as $value) {
    $this->db->where('invoice_id', $value);
    $this->db->update('invoice', $data);

    echo $this->db->last_query();
}
</code>```

The above code giving me Array to String conversion error.

Body:
I am trying to loop through multidimensional array to update the values in mysql table in codeignitor 3

I have an issue in looping through the values in multidimensional array

Below is my Multidimensional array:

$data = array(
    'invoice_id' => $invoice_id,
    'date' => $this->input->post('date',true),
    'commercial_invoice_number' => $this->input->post('commercial_invoice_number',true),
    'payment_type' => $this->input->post('payment_type',true)
);

When printing this array ,$data contains as below

(
    [invoice_id] => Array
        (
            [0] => 4549344712
            [1] => 4549344713
            [2] => 4549344814
        )
    [date] => Array
        (
            [0] => 25-11-2022
            [1] => 22-12-2022
            [2] => 12-10-2022
        )
    [commercial_invoice_number] => Array
        (
            [0] => NS202211-4
            [1] => NS202211-5
            [2] => NS202211-6
        )
    [payment_type] => Array
        (
            [0] => 0
            [1] => 1
            [2] => 0
        )
        )

print_r($invoice_id) returns as below

Array ( [0] => 4549344712 [1] => 4549344713 [2] => 4549344814 )

foreach ($invoice_id as $value) {
    $this->db->where('invoice_id', $value);
    $this->db->update('invoice', $data);

    echo $this->db->last_query();
}

The above code giving me Array to String conversion error.


问:
Cannot install and import tensorflow_federated in colab
I want to try a simple federated learning example in python. For it, I need to import tensorflow_federated package.

import tensorflow_federated as tff
```
<p>Here is the stack trace</p>
<pre class="lang-py prettyprint-override"><code>TypeError                                 Traceback (most recent call last)
<ipython-input-6-961ae1555cfa> in <module>
----> 1 import tensorflow_federated as tff

14 frames
/usr/lib/python3.8/typing.py in _type_check(arg, msg, is_argument)
    147         return arg
    148     if not callable(arg):
--> 149         raise TypeError(f"{msg} Got {arg!r:.100}.")
    150     return arg
    151

TypeError: Callable[[arg, ...], result]: each arg must be a type. Got Ellipsis.
</code>```

How should I resolve this error?

BTW, I read in a forum that the problem might be resolved by updating the python version, however it still exists despite I updated it to v3.9

The full stack trace is as follows (I had to submit a screenshot of it was misinterpreted by stackoverflow as some quotes and codes that are not in the right format)

Body:
I want to try a simple federated learning example in python. For it, I need to import tensorflow_federated package.

import tensorflow_federated as tff

Here is the stack trace

TypeError                                 Traceback (most recent call last)
<ipython-input-6-961ae1555cfa> in <module>
----> 1 import tensorflow_federated as tff

14 frames
/usr/lib/python3.8/typing.py in _type_check(arg, msg, is_argument)
    147         return arg
    148     if not callable(arg):
--> 149         raise TypeError(f"{msg} Got {arg!r:.100}.")
    150     return arg
    151

TypeError: Callable[[arg, ...], result]: each arg must be a type. Got Ellipsis.

How should I resolve this error?

BTW, I read in a forum that the problem might be resolved by updating the python version, however it still exists despite I updated it to v3.9

The full stack trace is as follows (I had to submit a screenshot of it was misinterpreted by stackoverflow as some quotes and codes that are not in the right format)


问:
Fill a column with a date that satisfies an id statement in Sap Phoenix Webi
I am trying to fill in the date needed column with the date that has 1 in Match comment and Rank columns. More specifically from all the comments I only need the ones that satisfy a pattern and then I ranked those based on activity date. I need to keep the date that satisfies the last two requirements and fill the DateNeeded column with this date no matter the content of the row.

Ex. Table

Code / activity.date / rank / matchComFlag / DateNeeded

Jfkffj 03/8/22 2 1 10/8/22

Jdiffi 10/8/22 1 1 10/8/22

So i created a variable that has the activity date formated where both flags are one but this only fills the row that applys and the others are blank.

How can i fill the whole DateNeeded column with the date I need?

Thank you in advance!


问:
How do I refer to a specific cell value(date) in Excel by using VBA and SQL?
I am trying to create a excel document where I can just write a date in a column in excel, and the date will update automatically in the data to the date in the column cell. Ex: if I change the date in a cell to 22/12/22 the data will change when running the query. I am quite new to VBA, so this might be a stupid question.. I am able extract the given dates when I write it manually in the query, however, I want to make it dynamic. This is the VBA query:

```<code> Option Explicit

    Sub project()

    Dim cn As ADODB.connection Dim rs As ADODB.Recordset Dim SQL As String

    Dim server_name As String, database_name As String Let server_name = "xxx" Let database_name = "xxx"

        Set cn = New ADODB.connection
        Set rs = New ADODB.Recordset

        cn.ConnectionString = "Provider=SQLNCLI11;Server=" & server_name & _
            ";database=" & database_name & ";Integrated Security=SSPI;"

            SQL = "Select * FROM table_name where value_date = '" & ThisWorkbook.Sheets(1).Range("A1").Value & "' " & ""

            cn.Open
            rs.Open SQL, cn

            ThisWorkbook.Sheets(2).Range("A2").CopyFromRecordset rs

            cn.Close

            Set cn = Nothing

    End Sub

</code>```

I have tried given the cell I am refering to a name, however it does not work.

Body:
I am trying to create a excel document where I can just write a date in a column in excel, and the date will update automatically in the data to the date in the column cell. Ex: if I change the date in a cell to 22/12/22 the data will change when running the query. I am quite new to VBA, so this might be a stupid question.. I am able extract the given dates when I write it manually in the query, however, I want to make it dynamic. This is the VBA query:

 Option Explicit

    Sub project()

    Dim cn As ADODB.connection Dim rs As ADODB.Recordset Dim SQL As String

    Dim server_name As String, database_name As String Let server_name = "xxx" Let database_name = "xxx"

        Set cn = New ADODB.connection
        Set rs = New ADODB.Recordset

        cn.ConnectionString = "Provider=SQLNCLI11;Server=" & server_name & _
            ";database=" & database_name & ";Integrated Security=SSPI;"

            SQL = "Select * FROM table_name where value_date = '" & ThisWorkbook.Sheets(1).Range("A1").Value & "' " & ""

            cn.Open
            rs.Open SQL, cn

            ThisWorkbook.Sheets(2).Range("A2").CopyFromRecordset rs

            cn.Close

            Set cn = Nothing

    End Sub

I have tried given the cell I am refering to a name, however it does not work.


问:
Is it possible to run python inside javascript code or inside jupyter despite having a javascript node kernel?
So I usually write courses and documentation in python with jupyter notebook, and today, I needed to write courses in javascript. I started writing them with the basic jupyter python kernel, and I wrote the code using with inline magic javascript (%%javascript). I installed the IJavaScript kernel to simplify writing and reading, and allow me to do stuff on several lines and keep my javascript variables from one cell to the other. It allows jupyter to run a nodejs kernel to execute code in cells.

But here comes the twists:

The inline magic doesn't work with javascript kernel, as it is stated by jupyter documentation that it is something specific to the python kernel. That is rather annoying as I wanted to load solutions to exercises with the %load  magic tag.

I had started writing quizes in my notebook before that with jupyterquiz, and they worked great, but now they don't work because, obviously, it's python code and javascript doesn't run python. As the jupyter magic tags don't work anymore, I don't have the option to just write something like %%python to run python code in cells.

I would like to be able to keep the kernel in javascript, but execute a python cell from time to time so that I can do quizes too, it's fun and more interactive.

Is there a way to make that happen ?

I tried using python-bridge, but it's been four years since its last update, and it doesn't seem to work properly. When executing the setup described in the documentation I had an error. The code I used was this, and it was identical to what is prescribed in python-bridge documentation :

'use strict';

let assert = require('assert');
let pythonBridge = require('python-bridge');
let python = pythonBridge();
```
<p>The <code>pythonBridge()</code> instruction gave me the following error :</p>
```node:internal/child_process:1066
      throw new ERR_INVALID_ARG_VALUE('stdio', stdio);
      ^

TypeError [ERR_INVALID_ARG_VALUE]: The argument 'stdio' is invalid. Received Transform {
  _readableState: ReadableState {
    objectMode: false,
    highWaterMark: 16384,
    buffer: BufferList { head: nu...
    at new NodeError (node:internal/errors:393:5)
    at node:internal/child_process:1066:13
    at Array.reduce (<anonymous>)
    at getValidStdio (node:internal/child_process:991:11)
    at ChildProcess.spawn (node:internal/child_process:355:11)
    at Object.spawn (node:child_process:743:9)
    at pythonBridge (/home/rozenn/work/node_modules/python-bridge/index.js:22:28)
    at evalmachine.<anonymous>:1:14
    at Script.runInThisContext (node:vm:129:12)
    at Object.runInThisContext (node:vm:313:38)
    at run ([eval]:1020:15)
    at onRunRequest ([eval]:864:18)
    at onMessage ([eval]:828:13)
    at process.emit (node:events:513:28)
    at emit (node:internal/child_process:937:14)
    at process.processTicksAndRejections (node:internal/process/task_queues:83:21)

```
<p>I am fairly new to javascript and especially node, I know enough to be able to illustrate algorithmic-related things to people who do code in javascript more than in python, but I haven't been using it in node so much so I don't really understand what that error means. I have found that github node issue that looks fairly related to my problem (?) but I don't really understand how the problem manifests in python-bridge nor how to translate the tweak proposed for my problem...</p>
<p>So I then tried to use pyscript. I figured that if markdown supports html, it should work, right ? I included this code in my cell:</p>
```
<py-script>
my python script importing the quiz module and reading the quiz question
</py-script>
```

It doesn't work either, I think markdown must not allow executable scripts in the html, which makes sense from a security point of view. So this code just shows the code written between the html tags and that's all.

Do you know ways to execute python inside of javascript kernel in jupyter notebook / jupyter lab, that I might not have thought about ?

Thank you for your time and have a nice day.

Body:
So I usually write courses and documentation in python with jupyter notebook, and today, I needed to write courses in javascript. I started writing them with the basic jupyter python kernel, and I wrote the code using with inline magic javascript (%%javascript). I installed the IJavaScript kernel to simplify writing and reading, and allow me to do stuff on several lines and keep my javascript variables from one cell to the other. It allows jupyter to run a nodejs kernel to execute code in cells.

But here comes the twists:

The inline magic doesn't work with javascript kernel, as it is stated by jupyter documentation that it is something specific to the python kernel. That is rather annoying as I wanted to load solutions to exercises with the %load  magic tag.

I had started writing quizes in my notebook before that with jupyterquiz, and they worked great, but now they don't work because, obviously, it's python code and javascript doesn't run python. As the jupyter magic tags don't work anymore, I don't have the option to just write something like %%python to run python code in cells.

I would like to be able to keep the kernel in javascript, but execute a python cell from time to time so that I can do quizes too, it's fun and more interactive.

Is there a way to make that happen ?

I tried using python-bridge, but it's been four years since its last update, and it doesn't seem to work properly. When executing the setup described in the documentation I had an error. The code I used was this, and it was identical to what is prescribed in python-bridge documentation :

'use strict';

let assert = require('assert');
let pythonBridge = require('python-bridge');
let python = pythonBridge();

The pythonBridge() instruction gave me the following error :

node:internal/child_process:1066
      throw new ERR_INVALID_ARG_VALUE('stdio', stdio);
      ^

TypeError [ERR_INVALID_ARG_VALUE]: The argument 'stdio' is invalid. Received Transform {
  _readableState: ReadableState {
    objectMode: false,
    highWaterMark: 16384,
    buffer: BufferList { head: nu...
    at new NodeError (node:internal/errors:393:5)
    at node:internal/child_process:1066:13
    at Array.reduce (<anonymous>)
    at getValidStdio (node:internal/child_process:991:11)
    at ChildProcess.spawn (node:internal/child_process:355:11)
    at Object.spawn (node:child_process:743:9)
    at pythonBridge (/home/rozenn/work/node_modules/python-bridge/index.js:22:28)
    at evalmachine.<anonymous>:1:14
    at Script.runInThisContext (node:vm:129:12)
    at Object.runInThisContext (node:vm:313:38)
    at run ([eval]:1020:15)
    at onRunRequest ([eval]:864:18)
    at onMessage ([eval]:828:13)
    at process.emit (node:events:513:28)
    at emit (node:internal/child_process:937:14)
    at process.processTicksAndRejections (node:internal/process/task_queues:83:21)

I am fairly new to javascript and especially node, I know enough to be able to illustrate algorithmic-related things to people who do code in javascript more than in python, but I haven't been using it in node so much so I don't really understand what that error means. I have found that github node issue that looks fairly related to my problem (?) but I don't really understand how the problem manifests in python-bridge nor how to translate the tweak proposed for my problem...

So I then tried to use pyscript. I figured that if markdown supports html, it should work, right ? I included this code in my cell:

<py-script>
my python script importing the quiz module and reading the quiz question
</py-script>

It doesn't work either, I think markdown must not allow executable scripts in the html, which makes sense from a security point of view. So this code just shows the code written between the html tags and that's all.

Do you know ways to execute python inside of javascript kernel in jupyter notebook / jupyter lab, that I might not have thought about ?

Thank you for your time and have a nice day.


问:
How to calculate size of a BatchQuery on client side in Cassandra?
I want to dynamically calculate the size of sum of rows inserted in a batchQuery so my size is below 50KBs.

I am using java driver.


问:
java.sql.SQLException: Invalid column type
I have a Oracle database where one of the column are XMLTYPE.
When I run the query in console it gives me back the column and the xml content.

```<code>SELECT DATA_RECEIVED
        FROM schema.taxCard
        WHERE FNR = (?) AND result = 'taxCardOK'
</code>```

This is working fine. But in Kotlin code I get the following error:

```<code>java.sql.SQLException: Invalid column type
at oracle.jdbc.driver.NamedTypeAccessor.getSQLXML(NamedTypeAccessor.java:438)
at oracle.jdbc.driver.OracleResultSetImpl.getSQLXML(OracleResultSetImpl.java:1251)
at com.zaxxer.hikari.pool.HikariProxyResultSet.getSQLXML(HikariProxyResultSet.java)
</code>```

My code looks like this:

```<code>    fun Connection.hentSkattekortPaFnr(
    fnr: String
): String {
   val statement =  prepareStatement(
        """
            SELECT DATA_RECEIVED
            FROM schema.taxCard
            WHERE FNR = (?) AND result = 'taxCardOK'
        """.trimIndent()
    ).apply {
        setString(1, fnr)
    }
    val resultSet = statement.executeQuery()
    val xml = resultSet.asSequence { resultSet.getSQLXML(1) }.first()
    return xml.string
}

    fun <T> ResultSet.asSequence(extract: () -> T ) : Sequence<T> = generateSequence{
    if (this.next()) extract() else null
    }
</code>```

What am I doing wrong?

Body:
I have a Oracle database where one of the column are XMLTYPE.
When I run the query in console it gives me back the column and the xml content.

SELECT DATA_RECEIVED
        FROM schema.taxCard
        WHERE FNR = (?) AND result = 'taxCardOK'

This is working fine. But in Kotlin code I get the following error:

java.sql.SQLException: Invalid column type
at oracle.jdbc.driver.NamedTypeAccessor.getSQLXML(NamedTypeAccessor.java:438)
at oracle.jdbc.driver.OracleResultSetImpl.getSQLXML(OracleResultSetImpl.java:1251)
at com.zaxxer.hikari.pool.HikariProxyResultSet.getSQLXML(HikariProxyResultSet.java)

My code looks like this:

    fun Connection.hentSkattekortPaFnr(
    fnr: String
): String {
   val statement =  prepareStatement(
        """
            SELECT DATA_RECEIVED
            FROM schema.taxCard
            WHERE FNR = (?) AND result = 'taxCardOK'
        """.trimIndent()
    ).apply {
        setString(1, fnr)
    }
    val resultSet = statement.executeQuery()
    val xml = resultSet.asSequence { resultSet.getSQLXML(1) }.first()
    return xml.string
}

    fun <T> ResultSet.asSequence(extract: () -> T ) : Sequence<T> = generateSequence{
    if (this.next()) extract() else null
    }

What am I doing wrong?


问:
I implemented TestAd from Admob in my android application, and now app get crashed and not opening
I had followed all the guidelines mentioned in Admob account for banner ad implementation.

dependency code

```<code>implementation 'com.google.android.gms:play-services-ads:21.4.0'
</code>```

Xml code

```<code><com.google.android.gms.ads.AdView
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:id="@+id/adView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_alignParentBottom="true"
    ads:adSize="BANNER"
    ads:adUnitId="ca-app-pub-9666981335006585/3735530644">
</com.google.android.gms.ads.AdView>
</code>```
```<code>//manifest code
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
</code>```
```<code><meta-data
    android:name="com.google.android.gms.ads.APPLICATION_ID"
    android:value="ca-app-pub-9666981335006585~5721182691"/>
</code>```
```<code>//MainActivity.java code
 AdView mAdView = findViewById(R.id.adView);
 AdRequest adRequest = new AdRequest.Builder().build();
 mAdView.loadAd(adRequest);`
</code>```

Help me to solve this error and find out the reason behind this, why my app is getting crash again and again after banner ad implementation. Even I had tried it on two different project.

Body:
I had followed all the guidelines mentioned in Admob account for banner ad implementation.

dependency code

implementation 'com.google.android.gms:play-services-ads:21.4.0'

Xml code

<com.google.android.gms.ads.AdView
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:id="@+id/adView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_alignParentBottom="true"
    ads:adSize="BANNER"
    ads:adUnitId="ca-app-pub-9666981335006585/3735530644">
</com.google.android.gms.ads.AdView>

//manifest code
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>

<meta-data
    android:name="com.google.android.gms.ads.APPLICATION_ID"
    android:value="ca-app-pub-9666981335006585~5721182691"/>

//MainActivity.java code
 AdView mAdView = findViewById(R.id.adView);
 AdRequest adRequest = new AdRequest.Builder().build();
 mAdView.loadAd(adRequest);`

Help me to solve this error and find out the reason behind this, why my app is getting crash again and again after banner ad implementation. Even I had tried it on two different project.


问:
Terminate while loop from a inner if condition in for loop
I have to terminate a while loop in javascript when a condition inside a inner for loop is met but this does not workas expected. below is my code snippet. it is not the actual script but a working one.

// Loop until Node appears
var nodeCreated = false;

var retries = 10;
while (retries > 0) {
  //Thread.sleep(10000);
  //sleep(i * 1000);
  retries--;
  //logger.addInfo("Waiting for node beeing created. " + retries.toString() + " retries left");
  console.log("number of retries left " + retries);
  //var nodes = nodeBeanPort.getNodes(c1);
  const nodes = "2,3";
  console.log(nodes.length);
  if (nodes.length === 0) {
    console.log("in equal to zero loop");
    continue;
  } else if (nodes.length > 0) {

    // Found node
    //logger.addInfo("Found Node in retry. " + retries.toString());
    for (var nodeIndex in nodes) {
      console.log("in for loop");
      console.log("nodes: " + nodes);
      var node = nodes[nodeIndex];
      console.log("node: " + node);
      console.log("nodeIndex: " + nodeIndex);
      //logger.addInfo("Found Node " + node);
      var x = 5;
      if (x === 5) {
        nodeCreated = true;
        break;

      }
    }
    //logger.addInfo("continuing loop ");
    continue;
    //break;
  } else {
    //for each(var node in nodes){
    //    logNode(node);
    //}
    nodeCreated = true;
    //ctxt.setFailed("Could not narrow down to the newly created node. Found " +
    //  nodes.length.toString() + " nodes with this name");
    break;
  }

} ```
</div>
</div>
</p>
<p>what i am looking for is that to end the script when below condition is true. like in this example:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>if (x === 5) {
            nodeCreated = true;
            break;
}           </code>```

I have also tried adding a lable but that does not work either.

Can someone suggest me how to solve this?

Body:
I have to terminate a while loop in javascript when a condition inside a inner for loop is met but this does not workas expected. below is my code snippet. it is not the actual script but a working one.

// Loop until Node appears
var nodeCreated = false;

var retries = 10;
while (retries > 0) {
  //Thread.sleep(10000);
  //sleep(i * 1000);
  retries--;
  //logger.addInfo("Waiting for node beeing created. " + retries.toString() + " retries left");
  console.log("number of retries left " + retries);
  //var nodes = nodeBeanPort.getNodes(c1);
  const nodes = "2,3";
  console.log(nodes.length);
  if (nodes.length === 0) {
    console.log("in equal to zero loop");
    continue;
  } else if (nodes.length > 0) {

    // Found node
    //logger.addInfo("Found Node in retry. " + retries.toString());
    for (var nodeIndex in nodes) {
      console.log("in for loop");
      console.log("nodes: " + nodes);
      var node = nodes[nodeIndex];
      console.log("node: " + node);
      console.log("nodeIndex: " + nodeIndex);
      //logger.addInfo("Found Node " + node);
      var x = 5;
      if (x === 5) {
        nodeCreated = true;
        break;

      }
    }
    //logger.addInfo("continuing loop ");
    continue;
    //break;
  } else {
    //for each(var node in nodes){
    //    logNode(node);
    //}
    nodeCreated = true;
    //ctxt.setFailed("Could not narrow down to the newly created node. Found " +
    //  nodes.length.toString() + " nodes with this name");
    break;
  }

}

what i am looking for is that to end the script when below condition is true. like in this example:

if (x === 5) {
            nodeCreated = true;
            break;
}

I have also tried adding a lable but that does not work either.

Can someone suggest me how to solve this?


问:
Counting the Occurrences of a string contains in a whole Pandas Data Frame [Not just a single column]
I would like to count suppose cmd.exe or svchost.exe occurence among the Pandas Dataframe without using for loop.

I can do that for a specific column but I would like to search the whole dataframe [all columns] and count a particular/given string.

This is sample data:

enter image description hereenter image description here

```<code>import pyarrow.parquet as pq
import pandas as pd
import pyarrow as pa

processes_dataset = pq.ParquetDataset('/dataset/w32processes')

df = processes_dataset.read().to_pandas()

print(df['name'].value_counts()['cmd.exe'])
</code>```

output: 10

Body:
I would like to count suppose cmd.exe or svchost.exe occurence among the Pandas Dataframe without using for loop.

I can do that for a specific column but I would like to search the whole dataframe [all columns] and count a particular/given string.

This is sample data:

enter image description hereenter image description here

import pyarrow.parquet as pq
import pandas as pd
import pyarrow as pa

processes_dataset = pq.ParquetDataset('/dataset/w32processes')

df = processes_dataset.read().to_pandas()

print(df['name'].value_counts()['cmd.exe'])

output: 10


问:
I want to limit the user input by date
I'm trying to limit the input of the user by Date, for example if the first input had this date: 2022-12-20, it would only accept dates in a weeks time, so the last possible date would be: 2022-12-27, 7 days later. I think I have to use a query to do this cause I understand that Hibernate does not have a function for such.

So I want to limit data input by date, example: first entry is 2022-12-20 I can only use 2022-12-21/22/23/.../27

this is the entity that I want to limit:

```<code>@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "planDay")
@JsonIgnoreProperties(value = {"planDaysId"})
public class PlanDay {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long planDaysId;

    @Column
    private Date planDate;

    @Column
    private String weekday;

    @ManyToOne
    @JoinColumn(name = "planId", nullable = false)
    private Plans plans;

    @ManyToOne
    @JoinColumn(name = "medsId", nullable = false)
    private Meds meds;

    @Column
    private int medsToTake;
}
</code>```

where planDate would be the attribute to limit. To save it I just do a planDayRepo.save(). Any Ideas?

Also my Controller and Service: Controller:

```<code>@PostMapping(value = "/plan/save")
    public String savePlans(@RequestBody List<PlanDay> plans) {

        return saveService.savePlans(plans);
    }
</code>```

Service (the for is just so I can update the piilNumber ignore it, I know I should not do it like that):

```<code>   public String savePlans(List<PlanDay> plans) {
        for (int i = 0; i < plans.size(); i++) {

            PlanDay planDay = plans.get(i);
            long medsId = planDay.getMeds().getMedsId();
            int medsToTake = planDay.getMedsToTake();
            int pillNumber = medsRepo.getReferenceById(medsId).getPillNumber();
            int pillUpdate = pillNumber - medsToTake;
            Meds updatePlanDay = medsRepo.findById(medsId).get();
            if (pillUpdate > 0) {
                updatePlanDay.setPillNumber(pillUpdate);
            } else {
                return "Error: No piils available";
            }
            planDayRepo.save(planDay);
        }
</code>```

Kind Regards

Title: I want to limit the user input by date

Body:
I'm trying to limit the input of the user by Date, for example if the first input had this date: 2022-12-20, it would only accept dates in a weeks time, so the last possible date would be: 2022-12-27, 7 days later. I think I have to use a query to do this cause I understand that Hibernate does not have a function for such.

So I want to limit data input by date, example: first entry is 2022-12-20 I can only use 2022-12-21/22/23/.../27

this is the entity that I want to limit:

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "planDay")
@JsonIgnoreProperties(value = {"planDaysId"})
public class PlanDay {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long planDaysId;

    @Column
    private Date planDate;

    @Column
    private String weekday;

    @ManyToOne
    @JoinColumn(name = "planId", nullable = false)
    private Plans plans;

    @ManyToOne
    @JoinColumn(name = "medsId", nullable = false)
    private Meds meds;

    @Column
    private int medsToTake;
}

where planDate would be the attribute to limit. To save it I just do a planDayRepo.save(). Any Ideas?

Also my Controller and Service: Controller:

@PostMapping(value = "/plan/save")
    public String savePlans(@RequestBody List<PlanDay> plans) {

        return saveService.savePlans(plans);
    }

Service (the for is just so I can update the piilNumber ignore it, I know I should not do it like that):

   public String savePlans(List<PlanDay> plans) {
        for (int i = 0; i < plans.size(); i++) {

            PlanDay planDay = plans.get(i);
            long medsId = planDay.getMeds().getMedsId();
            int medsToTake = planDay.getMedsToTake();
            int pillNumber = medsRepo.getReferenceById(medsId).getPillNumber();
            int pillUpdate = pillNumber - medsToTake;
            Meds updatePlanDay = medsRepo.findById(medsId).get();
            if (pillUpdate > 0) {
                updatePlanDay.setPillNumber(pillUpdate);
            } else {
                return "Error: No piils available";
            }
            planDayRepo.save(planDay);
        }

Kind Regards


问:
onedrive excel file not updating on scheduled refreshing
I stored an excel file on one drive and was able to manually refresh it on PowerBi Services BUT when I set it to scheduled refresh it will load for ever and not stop loading
What am I missing

I made sure that the path is correct and it is as it does refresh manually but not automatically


问:
I would to add integer to the path in firestore
```<code>for(int i = 0; int.parse(data['bedsAvailable']) > i; i++)
  //if((data.data() as Map)['boarderId'+'1'] != null)
  Padding(
    padding: EdgeInsets.all(16).copyWith(bottom: 0),
    child: Text(data['boarderId'+i.toString()],
      style: TextStyle(fontSize: 16,fontWeight: FontWeight.bold, color: Colors.green),
    ),
  )
</code>```

In every boarder Entered the room new boarderId created in the firestore.

I would like to display all the data in everyBoarderId in every loop.

Body:
for(int i = 0; int.parse(data['bedsAvailable']) > i; i++)
  //if((data.data() as Map)['boarderId'+'1'] != null)
  Padding(
    padding: EdgeInsets.all(16).copyWith(bottom: 0),
    child: Text(data['boarderId'+i.toString()],
      style: TextStyle(fontSize: 16,fontWeight: FontWeight.bold, color: Colors.green),
    ),
  )

In every boarder Entered the room new boarderId created in the firestore.

I would like to display all the data in everyBoarderId in every loop.


问:
Does API Gateway edge-optimized cache any http response?
It is written in the AWS doc that edge-optimized endpoints for API Gateway are using a managed Cloudfront distribution (to speed up accesses across the globe).

Since this is a "managed Cloudfront distribution", we cannot view the config of this Cloudfront distribution.

So my question is:

what is the configuration of this managed Cloudfront distribution ?

is this distribution configured to cache any content ?


问:
How to Remove Notification of Audio_manager package from notification panel in IOS
I'm using Audio_Manager package in my project, the problem is that Notification of audioplayer in notification panel not going  when i stop playing audios.

Tried searching on google but nothing found similar.


问:
Spring security requestmatcher enable swagger api download endpoint returns 401
I configured my openAPI endpoints so that I can download my swagger yml files on /docs.yml
I enabled the following:

```<code>.requestMatchers("/docs/**").permitAll()
</code>```

I also tried

```<code>.requestMatchers("/docs.yml").permitAll()
.requestMatchers("/docs/**").permitAll()
</code>```

Is there a way to enable the download of the file as well the endpoints under /docs/ ?

EDIT:

I'm using sping boot 3. Based on the docs, I have to include

```<code>        <dependency>
            <groupId>org.springdoc</groupId>
            <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
            <version>2.0.0</version>
        </dependency>
</code>```

for openApi support

Body:
I configured my openAPI endpoints so that I can download my swagger yml files on /docs.yml
I enabled the following:

.requestMatchers("/docs/**").permitAll()

I also tried

.requestMatchers("/docs.yml").permitAll()
.requestMatchers("/docs/**").permitAll()

Is there a way to enable the download of the file as well the endpoints under /docs/ ?

EDIT:

I'm using sping boot 3. Based on the docs, I have to include

        <dependency>
            <groupId>org.springdoc</groupId>
            <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
            <version>2.0.0</version>
        </dependency>

for openApi support


问:
JS code for WP Elementor page to exclude the content of popups from loading to increase page speed
I have a page built with WP Elementor with about 20 buttons that call different popups. The problem is that this page takes a very long time to load, the PageSpeed rating is below 20, but without connected popups the rating is 80, and the page loading speed is high.
The question is that if there is a way to add a  few lines of JS code to make popups exclude from the main page loading and loaded after clicking on each button?

P.S. I am not strong in JS, but I can insert the code to the corresponded field and make a small edit if necessary. Thanks!


问:
Html to Word Export using PHP Headers
I converted html and php pages to word with php headers, Now I want to add header image and footer for each every page of word documents with PHP headers.Please provide me a solution using PHP headers.

Below is the code i'am using for converting html to word.

```<code>$html ='Hello World";
$filename = 'mydoc';
header("Content-Type: application/vnd.msword");
header("Expires: 0");//no-cache
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");//no-cache
header("content-disposition: attachment;filename=".$filename.".doc");
echo "<html>";
echo $html;
echo "</html>";
</code>```

Title: Html to Word Export using PHP Headers

Body:
I converted html and php pages to word with php headers, Now I want to add header image and footer for each every page of word documents with PHP headers.Please provide me a solution using PHP headers.

Below is the code i'am using for converting html to word.

$html ='Hello World";
$filename = 'mydoc';
header("Content-Type: application/vnd.msword");
header("Expires: 0");//no-cache
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");//no-cache
header("content-disposition: attachment;filename=".$filename.".doc");
echo "";
echo $html;
echo "";


问:
Add Active Navigation Class Based on URL including sub paths
I'm using script form this article https://stackoverflow.com/a/20060541/14723575

```<code>$(function(){
    var current = location.pathname;
    $('#nav li a').each(function(){
        var $this = $(this);
        // if the current path is like this link, make it active
        if($this.attr('href').indexOf(current) !== -1){
            $this.addClass('active');
        }
    })
})
</code>```

The script works as it should when the pages are in the form: site.com/category site.com/category/subcategory etc, but the active class is lost when I want to go to the 2nd, 3rd etc. page via pagination, i.e. when the path is site.com/category/page/2/ site.com/category/page/3/ site.com/category/subcategory/page/2/ site.com/category/subcategory/page/3/ etc

What do I need to correct in the script so that the active class remains in the cases mentioned above ?

Body:
I'm using script form this article https://stackoverflow.com/a/20060541/14723575

$(function(){
    var current = location.pathname;
    $('#nav li a').each(function(){
        var $this = $(this);
        // if the current path is like this link, make it active
        if($this.attr('href').indexOf(current) !== -1){
            $this.addClass('active');
        }
    })
})

The script works as it should when the pages are in the form: site.com/category site.com/category/subcategory etc, but the active class is lost when I want to go to the 2nd, 3rd etc. page via pagination, i.e. when the path is site.com/category/page/2/ site.com/category/page/3/ site.com/category/subcategory/page/2/ site.com/category/subcategory/page/3/ etc

What do I need to correct in the script so that the active class remains in the cases mentioned above ?


问:
How to dynamically fetch credentials from database to tomcat-users.xml configuration file
I am trying to dynamically assign users and their roles using MYSQL database, and use it in Tomcat users configuration file (tomcat-users.xml)

All the example I have gone through on internet shows to statically add username, password and role. Like this:

```<code><role rolename="admin-gui"/>
  <role rolename="admin-script"/>

  <user username="probe" password="probe" roles="probeuser,poweruser,manager,manager-gui,poweruserplus" />
  <user username="tomcat" password="s3cret" roles="manager-gui,manager-script,manager-jmx,manager-status,admin-gui,admin-script"/>
</code>```

But I want to fetch the credentials from database.

I tried using JDBC Realm in server.xml config file, and created database conection through it. By following this tutorial

```<code><Realm  className="org.apache.catalina.realm.JDBCRealm"
        driverName="org.gjt.mm.mysql.Driver"
        connectionURL="jdbc:mysql://localhost:3306/tomcat_realm"
        connectionName="root" connectionPassword="12345678"
        userTable="users" userNameCol="user_name" userCredCol="user_pass"
        userRoleTable="user_roles" roleNameCol="role_name"
/>
</code>```

I don't know I am doing right or not. If I am right, then where to run SQL queries and how to insert the result to tomcat-users.xml configuration file.

Body:
I am trying to dynamically assign users and their roles using MYSQL database, and use it in Tomcat users configuration file (tomcat-users.xml)

All the example I have gone through on internet shows to statically add username, password and role. Like this:

<role rolename="admin-gui"/>
  <role rolename="admin-script"/>

  <user username="probe" password="probe" roles="probeuser,poweruser,manager,manager-gui,poweruserplus" />
  <user username="tomcat" password="s3cret" roles="manager-gui,manager-script,manager-jmx,manager-status,admin-gui,admin-script"/>

But I want to fetch the credentials from database.

I tried using JDBC Realm in server.xml config file, and created database conection through it. By following this tutorial

<Realm  className="org.apache.catalina.realm.JDBCRealm"
        driverName="org.gjt.mm.mysql.Driver"
        connectionURL="jdbc:mysql://localhost:3306/tomcat_realm"
        connectionName="root" connectionPassword="12345678"
        userTable="users" userNameCol="user_name" userCredCol="user_pass"
        userRoleTable="user_roles" roleNameCol="role_name"
/>

I don't know I am doing right or not. If I am right, then where to run SQL queries and how to insert the result to tomcat-users.xml configuration file.


问:
HTTP requests stuck in 'pending' state
Our tech-stack: VPS (ubuntu 20), asp.net core, identity server 4, reactjs, nginx, docker.
Router: Mikrotik rb4011igs+5hacq2hnd-in.

We rented a VPS and hosted our web-app on it with port 80. Everything works fine when requests to the web-app are made from outside of our office network f. e. from mobile network, vpn etc. But when requests are made from our office network some of them get stuck in 'pending' state. There are no traffic blocking rules on router’s firewall and it seems that 'pending' state only appears in our working hours (from 9 am till 6 pm).

Things we tried that didn’t work:

Disabling CORS.

Using traefik instead of nginx.

Changing ISP.

Changing VPS.

Turning off antiviruses, browser extensions, firewalls.

Using different browser.

Things that somehow solved the problem:

Making requests directly to the web-app bypassing nginx (working).

Changing external port on nginx container from 80 to 55643 (keeping internal port 80).

Removing bearer header from nginx requests.

We tried to monitor traffic using wireshark on client with tcpdump option enabled on nginx container. Wireshark shows us logging messages from the server and it looks like nginx successfully accepting requests then they are processed by the web application and then sent back to the client, but the client doesn’t accept the whole response. Tcpdump shows us that responses are being sent back to the client multiple times with a timeout of a few seconds. And judging by the messages from wireshark, the response comes in pieces.

Screenshot with successful request

Screenshot with pending request

We’re not sure what could be causing this problem so if you have any ideas or perhaps know other methods of solving this problem, please let us know.

Title: HTTP requests stuck in 'pending' state


问:
Golang recursive function call with timeout
I wrote a function that should be called every 5 seconds.

```<code>func (s *cacheService) ReloadCache() {
    // dosmt...

    <- time.After(time.Second * 5)

    s.ReloadCache()
}
</code>```

it looks easier than doing the same thing in a loop. But I wonder if such an implementation has problems with memory? Will the call stack be clogged or smt else?
is this option better?

```<code>func (s *cacheService) ReloadCache() {
    // dosmt...

    <- time.After(time.Second * 5)

    go s.ReloadCache()
}
</code>```

Body:
I wrote a function that should be called every 5 seconds.

func (s *cacheService) ReloadCache() {
    // dosmt...

    <- time.After(time.Second * 5)

    s.ReloadCache()
}

it looks easier than doing the same thing in a loop. But I wonder if such an implementation has problems with memory? Will the call stack be clogged or smt else?
is this option better?

func (s *cacheService) ReloadCache() {
    // dosmt...

    <- time.After(time.Second * 5)

    go s.ReloadCache()
}


问:
Rename an Excel sheet while keeping references up to date
I'm working on a script that takes an Excel template (containing some figures), fetches some data, computes some values and writes them in a spreadsheet based on the template. This works all fine but renaming the sheet breaks all references and as a consequence, all figures are broken.

Changing the sheet name doesn't update references in figures so I tried to manually update those references:

```<code>from openpyxl import load_workbook

wb = load_workbook(filename="my_template.xlsx")
sheet = wb["Old Sheet Name"]

for chart_index in range(len(sheet._charts)):
    chart = sheet._charts[chart_index]

    for series_index in range(len(chart.series)):
        sheet._charts[chart_index].series[series_index].cat.strRef.f = chart.series[
            series_index
        ].cat.strRef.f.replace("'Old Sheet Name'", "'New Sheet Name'")
</code>```

The result is as before, the figures are broken. Is there a list of fields I need to update so that the figures are aware of the renamed sheet and know where to look for data?

Body:
I'm working on a script that takes an Excel template (containing some figures), fetches some data, computes some values and writes them in a spreadsheet based on the template. This works all fine but renaming the sheet breaks all references and as a consequence, all figures are broken.

Changing the sheet name doesn't update references in figures so I tried to manually update those references:

from openpyxl import load_workbook

wb = load_workbook(filename="my_template.xlsx")
sheet = wb["Old Sheet Name"]

for chart_index in range(len(sheet._charts)):
    chart = sheet._charts[chart_index]

    for series_index in range(len(chart.series)):
        sheet._charts[chart_index].series[series_index].cat.strRef.f = chart.series[
            series_index
        ].cat.strRef.f.replace("'Old Sheet Name'", "'New Sheet Name'")

The result is as before, the figures are broken. Is there a list of fields I need to update so that the figures are aware of the renamed sheet and know where to look for data?


问:
Wordpress - add a plus and minus button with the quantity number between them to the product variation which when pressed add the variant to the cart
I need a plus and minus button with the quantity number between them for each product variation when you press the plus it has to add the item to the cart and when pressed again, if is alredy in the cart, increase the quantity.

With the minus button when pressed, decrease the quantity in the cart or if the quantity is 0, delete it from the cart, anyone can help?


问:
Is there any way to use Indexer outside the clipse project when parsing C++ projects using CDT？
Indexer is very powerful when parsing C++ projects using CDTS. However, getting an indexer inevitably leads to a problem: "eclipse workspace is closed". Is there any way to use indexer outside of an eclipse project?

Solution about using indexer outside of eclipse projects?


问:
How to get Wear OS version provide by google?
I am a android developer and i have devloped a application for wear watch, but i need to find current version of wearOS which are provide by google(Not a Home version) .
How to get programatically wearOS version in in my devlopment code. For better understanding you can see my attechment.[enter image description here](https://i.stack.imgur.com/j6aE5.png)

I am using below code in my devlopement code

```<code>val info: PackageInfo = packageManager.getPackageInfo(
    "com.google.android.wearable.app",
    0
)
return info.versionName
</code>```

Body:
I am a android developer and i have devloped a application for wear watch, but i need to find current version of wearOS which are provide by google(Not a Home version) .
How to get programatically wearOS version in in my devlopment code. For better understanding you can see my attechment.[enter image description here](https://i.stack.imgur.com/j6aE5.png)

I am using below code in my devlopement code

val info: PackageInfo = packageManager.getPackageInfo(
    "com.google.android.wearable.app",
    0
)
return info.versionName


问:
Vue 3 - refs inside v-for not working when onMounted event happens
I have following code for Vue (script setup):

const { freeTables, usedTables } = storeToRefs(useTableStore())

let mineButton = ref()

const itemRefs = ref([])

onMounted(() => {
  mineButton = document.getElementById('mine-tables')

  const urlPath = window.location.pathname.slice(1).split('/')

  if (urlPath[0] === 'tables' && Number.isInteger(+urlPath[1])) {
    let currentTable = document.getElementById(`table-${urlPath[1]}`)

    // console.log(currentTable);
  }
})
```
<p>And on template part I have this code:</p>
<pre class="lang-html prettyprint-override"><code><tr
  @mouseenter="removeClass"
  v-for="table in usedTables"
  ref="itemRefs"
  :key="table.id"
  role="button"
  :id="`table-${table.id}`"
>
  <td
    v-tooltip="$t('tables.tooltip.show')"
    class="h5"
    @click="tableOrder(table)"
  >
    {{ table.name }}
  </td>

  <td class="col-1 text-end h3">
    <span class="badge bg-dark">
      4 <i class="fa-solid fa-chair"></i>
    </span>
  </td>

  <td
    @click="takeTable(table.id)"
    v-tooltip="$t('tables.tooltip.take')"
    v-if="+table.userID !== +userData.id && +table.waiterID !== +userData.id"
  >
    <font-awesome-icon icon="fa-solid fa-people-robbery"></font-awesome-icon>
  </td>
</tr>
</code>```

The issue is the following: once the onMounted event is fired, the itemRefs is empty (without any elements inside). But if the hot reload is performed the itemRefs have proper elements. What am I doing wrong here?

Body:
I have following code for Vue (script setup):

const { freeTables, usedTables } = storeToRefs(useTableStore())

let mineButton = ref()

const itemRefs = ref([])

onMounted(() => {
  mineButton = document.getElementById('mine-tables')

  const urlPath = window.location.pathname.slice(1).split('/')

  if (urlPath[0] === 'tables' && Number.isInteger(+urlPath[1])) {
    let currentTable = document.getElementById(`table-${urlPath[1]}`)

    // console.log(currentTable);
  }
})

And on template part I have this code:

<tr
  @mouseenter="removeClass"
  v-for="table in usedTables"
  ref="itemRefs"
  :key="table.id"
  role="button"
  :id="`table-${table.id}`"
>

    {{ table.name }}

      4

The issue is the following: once the onMounted event is fired, the itemRefs is empty (without any elements inside). But if the hot reload is performed the itemRefs have proper elements. What am I doing wrong here?


问:
EF6 use TVF containing Temporal table relationship
I need to write in SQL Server 2019 a TVF that queries 2 temporal tables that have a relationship like Student and Course (both temporal table).
How can I write the TVF so that EF6 recognize the entity as
Student
--> Courses[]
?

For design reason I can't use EF core.

(This is an example. In my real case I have more relationship between temporal table)

I tried to write a TVF specifying al the columns of all the tables in relationship but, in my case, I have several relationship with big tables so I might have a TVF with more than 100 columns!


问:
Get rectangles instead of text in geoserver legend
I am using Geoserver to produce WMS layers. I am from Georgia (Country not US state), so we need to have text in our language. We use utf-8 characters, but in WMS Legend get rectangles instead of text. In pevious version of geoserver it worked properly.

here is code of SLD

```<code><?xml version="1.0" encoding="UTF-8"?>
<StyledLayerDescriptor version="1.0.0"
    xsi:schemaLocation="http://www.opengis.net/sld StyledLayerDescriptor.xsd"
    xmlns="http://www.opengis.net/sld"
    xmlns:ogc="http://www.opengis.net/ogc"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <NamedLayer>
    <Name>უძრავი ძეგლები</Name>
    <UserStyle>
      <Title>uZravi Zeglebi</Title>
      <FeatureTypeStyle>
        <Rule>
          <Name>კულტურული მემკვიდრეობის ობიექტი</Name>
          <ogc:Filter>
            <ogc:PropertyIsLike wildCard="%" singleChar="#" escape="!">
              <ogc:PropertyName>status</ogc:PropertyName>
              <ogc:Literal>კულტურული მემკვიდრეობის ობიექტი%</ogc:Literal>
            </ogc:PropertyIsLike>
          </ogc:Filter>
          <PolygonSymbolizer>
         <Fill>
           <CssParameter name="fill">#ff6e6e</CssParameter>
         </Fill>
       </PolygonSymbolizer>
        </Rule>
      </FeatureTypeStyle>
      <FeatureTypeStyle>
        <Rule>
        <Name>kulturuli memkvidreobis dzegli</Name>
          <ogc:Filter>
            <ogc:PropertyIsLike wildCard="%" singleChar="#" escape="!">
              <ogc:PropertyName>status</ogc:PropertyName>
              <ogc:Literal>კულტურული მემკვიდრეობის ძეგლი%</ogc:Literal>
            </ogc:PropertyIsLike>
          </ogc:Filter>
          <PolygonSymbolizer>
         <Fill>
           <CssParameter name="fill">#8d1818</CssParameter>
         </Fill>
       </PolygonSymbolizer>
        </Rule>
      </FeatureTypeStyle>
      <FeatureTypeStyle>
        <Rule>
        <Name>obieqti statusis gareshe</Name>
          <ogc:Filter>
            <ogc:PropertyIsLike wildCard="%" singleChar="#" escape="!">
              <ogc:PropertyName>status</ogc:PropertyName>
              <ogc:Literal>ობიექტი სტატუსის გარეშე%</ogc:Literal>
            </ogc:PropertyIsLike>
          </ogc:Filter>
          <PolygonSymbolizer>
         <Fill>
           <CssParameter name="fill">#58ceeb</CssParameter>
         </Fill>
       </PolygonSymbolizer>
        </Rule>
      </FeatureTypeStyle>
    </UserStyle>
  </NamedLayer>
</StyledLayerDescriptor>
</code>```

I make setting to utf-8, everywhere find such settings.

Body:
I am using Geoserver to produce WMS layers. I am from Georgia (Country not US state), so we need to have text in our language. We use utf-8 characters, but in WMS Legend get rectangles instead of text. In pevious version of geoserver it worked properly.

here is code of SLD

<?xml version="1.0" encoding="UTF-8"?>

I make setting to utf-8, everywhere find such settings.


问:
Program failing after adding Endpoint security framework entitlement to Xcode project
Hi I am new to Xcode development and wanted to check ES events, but getting the below error while execution after adding endpoint-security.client entitlement to the project.

The application cannot be opened for an unexpected reason, error=Error Domain=RBSRequestErrorDomain Code=5 "Launch failed." UserInfo={NSLocalizedFailureReason=Launch failed., NSUnderlyingError=0x6000035b6550 {Error Domain=NSPOSIXErrorDomain Code=153 "Unknown error: 153" UserInfo={NSLocalizedDescription=Launchd job spawn failed}}}

Is it necessary the Developer id to be enrolled? Can someone tell me some fix?
And is it possible to get ES events using python?

Added the entitlement and tried running as sudo user after building the project


问:
How can we make axisline inside gauge chart clickable in apache echarts?
I want to make the colored axis line clickable.I want the colored section to be clickable and hoverable.
In my case:

Expected changes:
The colored section to be clickable and hoverable.

```<code>option = {
  tooltip: {
    formatter: '{a} <br/>{b} : {c}%'
  },
  series: [
    {
      name: 'Pressure',
      type: 'gauge',
      // progress: {
      //   show: true
      // },
      axisLine: {
      lineStyle: {
        opacity: 0.5,
        onclick: function (event) {
          console.log(event);
        },
        color: [
          [0, '#00f'],
          [0.25, '#0ff'],
          [0.5, '#0f0'],
          [0.75, '#ff0'],
          [1, '#f00']
        ]
      }
    },
      detail: {
        valueAnimation: true,
        formatter: '{value}'
      },
      data: [
        {
          value: 50,
          name: 'SCORE'
        }
      ]
    }
  ]
};

myChart.on('click', function(params) {

  console.log('Params',params);
});
</code>```

Body:
I want to make the colored axis line clickable.I want the colored section to be clickable and hoverable.
In my case:

Expected changes:
The colored section to be clickable and hoverable.

option = {
  tooltip: {
    formatter: '{a}
{b} : {c}%'
  },
  series: [
    {
      name: 'Pressure',
      type: 'gauge',
      // progress: {
      //   show: true
      // },
      axisLine: {
      lineStyle: {
        opacity: 0.5,
        onclick: function (event) {
          console.log(event);
        },
        color: [
          [0, '#00f'],
          [0.25, '#0ff'],
          [0.5, '#0f0'],
          [0.75, '#ff0'],
          [1, '#f00']
        ]
      }
    },
      detail: {
        valueAnimation: true,
        formatter: '{value}'
      },
      data: [
        {
          value: 50,
          name: 'SCORE'
        }
      ]
    }
  ]
};

myChart.on('click', function(params) {

  console.log('Params',params);
});


问:
UIScreen.main is deprecating. What should I replace it with?
I'm using swiftUI and I want the width and height of the screen.

It says .main will be depreciated. What should I replace it with? What's the new approach?

I have this code in my project

```<code>import SwiftUI

let width  = UIScreen.main.bounds.width
let height = UIScreen.main.bounds.height
</code>```

I declared this in a global file.

I'm using iOS 16.2 (the latest xcode & iOS)

Body:
I'm using swiftUI and I want the width and height of the screen.

It says .main will be depreciated. What should I replace it with? What's the new approach?

I have this code in my project

import SwiftUI

let width  = UIScreen.main.bounds.width
let height = UIScreen.main.bounds.height

I declared this in a global file.

I'm using iOS 16.2 (the latest xcode & iOS)


问:
How exactly does binding work for list of ViewModels in ReactiveUI
I am currently learning ReactiveUI for WPF. I have rebuilt the following example project and tried to understand it: https://www.reactiveui.net/docs/getting-started/compelling-example

I could understand everything so far, except for one thing. In the example, a list of ViewModels (NugetDetailsViewModel) is connected to a ListBox in a view. I would like to understand what happens in the binding in the background, so that in the end the actual view (NugetDetailsView) is loaded and displayed in the application correctly.

In the documentation in the View Location section (https://www.reactiveui.net/docs/handbook/view-location/) it only says the following:

```<code>// Now ListBox automatically gets a DataTemplate
this.OneWayBind(ViewModel, vm => vm.ToasterList, v => v.ToasterList.ItemsSource);
</code>```

Unfortunately, the information doesn't help. Maybe you can help me further.
Thank you!

Body:
I am currently learning ReactiveUI for WPF. I have rebuilt the following example project and tried to understand it: https://www.reactiveui.net/docs/getting-started/compelling-example

I could understand everything so far, except for one thing. In the example, a list of ViewModels (NugetDetailsViewModel) is connected to a ListBox in a view. I would like to understand what happens in the binding in the background, so that in the end the actual view (NugetDetailsView) is loaded and displayed in the application correctly.

In the documentation in the View Location section (https://www.reactiveui.net/docs/handbook/view-location/) it only says the following:

// Now ListBox automatically gets a DataTemplate
this.OneWayBind(ViewModel, vm => vm.ToasterList, v => v.ToasterList.ItemsSource);

Unfortunately, the information doesn't help. Maybe you can help me further.
Thank you!