问:
Trying to use devcontainers with a docker compose file immediately fails
I'm trying to use devcontainers with docker compose. I get this error immediately:

```<code>Command 'Dev Containers: Rebuild and Reopen in Container' resulted in an error (Command failed: /private/var/folders/vw/m_7gmll54yb0cnfp687dxh740000gq/T/AppTranslocation/1485CA8A-FFAA-4796-BA55-5928911F8CB3/d/Visual Studio Code.app/Contents/Frameworks/Code Helper.app/Contents/MacOS/Code Helper --ms-enable-electron-run-as-node /Users/me/.vscode/extensions/ms-vscode-remote.remote-containers-0.266.1/dist/spec-node/devContainersSpecCLI.js read-configuration --workspace-folder /Users/me/myfolder/myproject --log-level debug --log-format json --config /Users/me/myfolder/myproject/.devcontainer/devcontainer.json --include-merged-configuration --mount-workspace-git-root true)
</code>```

Where do I even go to see logs?

I confirmed my compose file works fine when I run it with the regular docker compose command.

This is my dev container config:

```<code>{
"name": "Python 3",
"dockerComposeFile": [
    "../docker-compose.yml"
],
"service": "devcontainer_testenv",
"workspaceFolder": "/app",
"shutdownAction": "stopCompose",
// Configure tool-specific properties.
"customizations": {
    // Configure properties specific to VS Code.
    "vscode": {
        // Set *default* container specific settings.json values on container create.
        "settings": {
            "terminal.integrated.profiles.linux": {
                "bash": {
                    "path": "/bin/bash"
                }
            },
            "python.defaultInterpreterPath": "/usr/local/bin/python",
            "python.languageServer": "Default",
            "python.linting.enabled": true,
            "python.linting.pylintEnabled": true,
            "python.formatting.autopep8Path": "/usr/local/py-utils/bin/autopep8",
            "python.formatting.blackPath": "/usr/local/py-utils/bin/black",
            "python.formatting.yapfPath": "/usr/local/py-utils/bin/yapf",
            "python.linting.banditPath": "/usr/local/py-utils/bin/bandit",
            "python.linting.flake8Path": "/usr/local/py-utils/bin/flake8",
            "python.linting.mypyPath": "/usr/local/py-utils/bin/mypy",
            "python.linting.pycodestylePath": "/usr/local/py-utils/bin/pycodestyle",
            "python.linting.pydocstylePath": "/usr/local/py-utils/bin/pydocstyle",
            "python.linting.pylintPath": "/usr/local/py-utils/bin/pylint"
        },
        // Add the IDs of extensions you want installed when the container is created.
        "extensions": [
            "ms-python.python",
            "ms-python.vscode-pylance"
        ]
    }
}
</code>```

}

I feel totally helpless, where do I see an error log? It pops this error in less than a second when I try to run Dev Containers: Reopen and Rebuild.

I have "Use Docker Compose V2" enabled as well.

Body:
I'm trying to use devcontainers with docker compose. I get this error immediately:

Command 'Dev Containers: Rebuild and Reopen in Container' resulted in an error (Command failed: /private/var/folders/vw/m_7gmll54yb0cnfp687dxh740000gq/T/AppTranslocation/1485CA8A-FFAA-4796-BA55-5928911F8CB3/d/Visual Studio Code.app/Contents/Frameworks/Code Helper.app/Contents/MacOS/Code Helper --ms-enable-electron-run-as-node /Users/me/.vscode/extensions/ms-vscode-remote.remote-containers-0.266.1/dist/spec-node/devContainersSpecCLI.js read-configuration --workspace-folder /Users/me/myfolder/myproject --log-level debug --log-format json --config /Users/me/myfolder/myproject/.devcontainer/devcontainer.json --include-merged-configuration --mount-workspace-git-root true)

Where do I even go to see logs?

I confirmed my compose file works fine when I run it with the regular docker compose command.

This is my dev container config:

{
"name": "Python 3",
"dockerComposeFile": [
    "../docker-compose.yml"
],
"service": "devcontainer_testenv",
"workspaceFolder": "/app",
"shutdownAction": "stopCompose",
// Configure tool-specific properties.
"customizations": {
    // Configure properties specific to VS Code.
    "vscode": {
        // Set *default* container specific settings.json values on container create.
        "settings": {
            "terminal.integrated.profiles.linux": {
                "bash": {
                    "path": "/bin/bash"
                }
            },
            "python.defaultInterpreterPath": "/usr/local/bin/python",
            "python.languageServer": "Default",
            "python.linting.enabled": true,
            "python.linting.pylintEnabled": true,
            "python.formatting.autopep8Path": "/usr/local/py-utils/bin/autopep8",
            "python.formatting.blackPath": "/usr/local/py-utils/bin/black",
            "python.formatting.yapfPath": "/usr/local/py-utils/bin/yapf",
            "python.linting.banditPath": "/usr/local/py-utils/bin/bandit",
            "python.linting.flake8Path": "/usr/local/py-utils/bin/flake8",
            "python.linting.mypyPath": "/usr/local/py-utils/bin/mypy",
            "python.linting.pycodestylePath": "/usr/local/py-utils/bin/pycodestyle",
            "python.linting.pydocstylePath": "/usr/local/py-utils/bin/pydocstyle",
            "python.linting.pylintPath": "/usr/local/py-utils/bin/pylint"
        },
        // Add the IDs of extensions you want installed when the container is created.
        "extensions": [
            "ms-python.python",
            "ms-python.vscode-pylance"
        ]
    }
}

}

I feel totally helpless, where do I see an error log? It pops this error in less than a second when I try to run Dev Containers: Reopen and Rebuild.

I have "Use Docker Compose V2" enabled as well.


来源: stackexchange

问:
Why both absolute change and relative change populated with no output for function build in python?
I wrote function in pandas  to calculate absolute change and relative change of amount basis on place, year. However I am getting no output for both absolute change and relative change. Below is the code

```<code>#Importing the libraries
import pandas as pd
import numpy as np
#Building function
def calculate_change(df):
    df['absolute_change'] = df.groupby(['place', 'year'])['amount'].diff()
    df['relative_change'] = df.groupby(['place', 'year'])['amount'].pct_change()
    return df
#Sample dataframe
df = pd.DataFrame({'place': ['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B'],
                    'year': [2010, 2011, 2012, 2013, 2014, 2010, 2011, 2012, 2013, 2014],
                    'amount': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]})
calculate_change(df)
</code>```

Looking for an output as below:

ContentLicense: CC BY-SA 4.0

Body:
I wrote function in pandas  to calculate absolute change and relative change of amount basis on place, year. However I am getting no output for both absolute change and relative change. Below is the code

#Importing the libraries
import pandas as pd
import numpy as np
#Building function
def calculate_change(df):
    df['absolute_change'] = df.groupby(['place', 'year'])['amount'].diff()
    df['relative_change'] = df.groupby(['place', 'year'])['amount'].pct_change()
    return df
#Sample dataframe
df = pd.DataFrame({'place': ['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B'],
                    'year': [2010, 2011, 2012, 2013, 2014, 2010, 2011, 2012, 2013, 2014],
                    'amount': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]})
calculate_change(df)

Looking for an output as below:


问:
bot.get_chat_member() say data about user that is not subscribed to specified chat
I have the following code:

```<code>import telebot

bot = telebot.TeleBot("token")
channels_to_subscribe = ["@kinonovelties","@marvelnews4"]

def is_subscribed(chat_id, user_id):
    try:
        bot.get_chat_member(chat_id, user_id)
        print(chat_id)
        # print(bot.get_chat_member(chat_id, user_id))
        return False
    except:
        return True

def get_not_subscribed(uid):
    returned = []
    for channel in channels_to_subscribe:
        print(str(is_subscribed(channel,uid))+":"+channel+":"+str(uid)+":"+str(bot.get_chat(uid)))
        if is_subscribed(channel,uid) == False:
            returned.append(channel)
    # print(returned)
    return returned;

@bot.message_handler()
def message_handler(message):
    text = message.text
    uid = message.from_user.id
    usr = message.from_user

    if text == "/start":
        reply_markup = telebot.types.ReplyKeyboardMarkup()
        reply_markup.add(telebot.types.KeyboardButton("Новинки "))
        reply_markup.add(telebot.types.KeyboardButton("Популярные ✨"))
        reply_markup.add(telebot.types.KeyboardButton("Поиск по коду "))
        reply_markup.add(telebot.types.KeyboardButton("Сейчас смотрят "))
        bot.send_message(uid, "Выберите интересующую вас категорию:",reply_markup=reply_markup)
    elif text == "Новинки ":
        if not get_not_subscribed(uid) == []:
            string = ""
            print(get_not_subscribed(uid))
            for s in get_not_subscribed(uid):
                string += s+","

            bot.send_message(uid, "Чел, ты не подписан на каналы:\n\n"+string)

bot.infinity_polling(0)
</code>```

If user subscribed to specified channel, bot just do anything. Else, it write channels, what user need to subscribe. But, bot tells that user subscribed to all specified channels, while user subscribed to only one of this channels. What is it? How to fix it?

I try to output the result of bot.get_chat_member(), it gave correct data about user that is not subscribed to channel.

Body:
I have the following code:

import telebot

bot = telebot.TeleBot("token")
channels_to_subscribe = ["@kinonovelties","@marvelnews4"]

def is_subscribed(chat_id, user_id):
    try:
        bot.get_chat_member(chat_id, user_id)
        print(chat_id)
        # print(bot.get_chat_member(chat_id, user_id))
        return False
    except:
        return True

def get_not_subscribed(uid):
    returned = []
    for channel in channels_to_subscribe:
        print(str(is_subscribed(channel,uid))+":"+channel+":"+str(uid)+":"+str(bot.get_chat(uid)))
        if is_subscribed(channel,uid) == False:
            returned.append(channel)
    # print(returned)
    return returned;

@bot.message_handler()
def message_handler(message):
    text = message.text
    uid = message.from_user.id
    usr = message.from_user

    if text == "/start":
        reply_markup = telebot.types.ReplyKeyboardMarkup()
        reply_markup.add(telebot.types.KeyboardButton("Новинки "))
        reply_markup.add(telebot.types.KeyboardButton("Популярные ✨"))
        reply_markup.add(telebot.types.KeyboardButton("Поиск по коду "))
        reply_markup.add(telebot.types.KeyboardButton("Сейчас смотрят "))
        bot.send_message(uid, "Выберите интересующую вас категорию:",reply_markup=reply_markup)
    elif text == "Новинки ":
        if not get_not_subscribed(uid) == []:
            string = ""
            print(get_not_subscribed(uid))
            for s in get_not_subscribed(uid):
                string += s+","

            bot.send_message(uid, "Чел, ты не подписан на каналы:\n\n"+string)

bot.infinity_polling(0)

If user subscribed to specified channel, bot just do anything. Else, it write channels, what user need to subscribe. But, bot tells that user subscribed to all specified channels, while user subscribed to only one of this channels. What is it? How to fix it?

I try to output the result of bot.get_chat_member(), it gave correct data about user that is not subscribed to channel.


问:
Brownie cannot interact with Contracts Outside
```<code>I am trying to call the USDT contract on the Polygon Mumbai testnet.  The following is my python code to be executed:

    from brownie import accounts, network, Contract
    from web3 import Web3

    POLYGON_USDT = "0x28e0d6c548F51D41c4677151C3a06eC508235278"

    def main():
        print("testing")
        print(f"The active network is {network.show_active()}")
        usdt = Contract(POLYGON_USDT)
        print(usdt.info())

</code>```

After running brownie run .\scripts\call_contract.py --network polygon-test,
the following error code shown up:

```<code>Brownie v1.18.1 - Python development framework for Ethereum

ContractProject is the active project.

Running 'scripts\call_contract.py::main'...
testing
The active network is polygon-test
  File "C:\Users\hello\.local\pipx\venvs\eth-brownie\lib\site-packages\brownie\_cli\run.py", line 51, in main
    return_value, frame = run(
  File "C:\Users\hello\.local\pipx\venvs\eth-brownie\lib\site-packages\brownie\project\scripts.py", line 103, in run
    return_value = f_locals[method_name](*args, **kwargs)
  File ".\scripts\call_contract.py", line 11, in main
    usdt = Contract(POLYGON_USDT)
  File "C:\Users\hello\.local\pipx\venvs\eth-brownie\lib\site-packages\brownie\network\contract.py", line 879, in __init__
    raise ValueError(f"Unknown contract address: '{address}'")
ValueError: Unknown contract address: '0x28e0d6c548F51D41c4677151C3a06eC508235278'
</code>```

As I am quite confident that the contract address is correct, we can find the contract on polygonscan: https://mumbai.polygonscan.com/token/0x28e0d6c548f51d41c4677151c3a06ec508235278.

```<code></code>```

Body:
I am trying to call the USDT contract on the Polygon Mumbai testnet.  The following is my python code to be executed:

    from brownie import accounts, network, Contract
    from web3 import Web3

    POLYGON_USDT = "0x28e0d6c548F51D41c4677151C3a06eC508235278"

    def main():
        print("testing")
        print(f"The active network is {network.show_active()}")
        usdt = Contract(POLYGON_USDT)
        print(usdt.info())

After running brownie run .\scripts\call_contract.py --network polygon-test,
the following error code shown up:

Brownie v1.18.1 - Python development framework for Ethereum

ContractProject is the active project.

Running 'scripts\call_contract.py::main'...
testing
The active network is polygon-test
  File "C:\Users\hello\.local\pipx\venvs\eth-brownie\lib\site-packages\brownie\_cli\run.py", line 51, in main
    return_value, frame = run(
  File "C:\Users\hello\.local\pipx\venvs\eth-brownie\lib\site-packages\brownie\project\scripts.py", line 103, in run
    return_value = f_locals[method_name](*args, **kwargs)
  File ".\scripts\call_contract.py", line 11, in main
    usdt = Contract(POLYGON_USDT)
  File "C:\Users\hello\.local\pipx\venvs\eth-brownie\lib\site-packages\brownie\network\contract.py", line 879, in __init__
    raise ValueError(f"Unknown contract address: '{address}'")
ValueError: Unknown contract address: '0x28e0d6c548F51D41c4677151C3a06eC508235278'

As I am quite confident that the contract address is correct, we can find the contract on polygonscan: https://mumbai.polygonscan.com/token/0x28e0d6c548f51d41c4677151c3a06ec508235278.


问:
No change in url while integrating a javascript code inside the Div of another website
I am integrating a javascript code(with file name) in a div of customer Website page. This javascript code is creating many items with short detail in a div. when we click for more detail of a perticular item then it displays the more detail in the same div without changing the Url. I want that when we click on more detail then it should also add the id of item in the Url.

Customer add below line of code in their div.In Objektlist.js i have defined click event for more details. Here I am using 'XMLHttpRequest' for fetching the more details of the item.

```<code><div id="item-container" data-id="021"></div>
<script async src="https://www.example.com/wp-content/themes/abc/js/objektlist.js"></script>
</code>```

I am using PHP, Javascript, Ajax

Url of Customer Website is when it is showing all the items with less detail and more item.
https://www.example.de/offers/

I want when anyone click on more detail then Url should change like below:
https://www.example.de/offers/#item-123    or https://www.example.de/offers?item=123

This is my more detail button html code

```<code><div class="content-bottom">
                        <div class="item-link" data-id="{{ $objekt->id }}" style="margin-top: 10px;margin-bottom:10px;">More detail</div>
                    </div>
</code>```

Here is my main code for getItem:

getItem(id){

```<code>    if(this.loading){ return; }

    this.loading = true;
    this.container.classList.toggle('fade-out');

    var data = [
        'objektliste=' + this.objektliste_id,
    ];
    data = encodeURI(data.join('&'));

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = () => {
        if (xhr.readyState === 4){

            this.container.innerHTML = xhr.responseText;
            console.log(this.container.innerHTML);
            this.container.classList.toggle('fade-out');

            this.addScripts([
                //'//google.com/recaptcha/api.js?render=6LdQN5wUAAAAAL7skFoMkYv5_9fg1WCrztd_ALRc',
                //JR: '//maps.google.com/maps/api/js?key=AIzaSyAoux8Z8eQWOs06n4hJacb_IATFKOQ62oo&libraries=drawing',
                //'//anbieter.ivd24immobilien.de/js/jquery-1.8.0.js',
                'https://code.jquery.com/jquery-3.3.1.min.js',
                'https://code.jquery.com/jquery-migrate-1.4.1.min.js',
                //'https://www.ivd24immobilien.de/wp-content/themes/ivd24/js/jquery-migrate-1.4.1.minimmo1.js',
                //'//cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js',
                'https://npmcdn.com/tether@1.2.4/dist/js/tether.min.js',

                this.iurl+'/js/objektlisten/item.js',
            ], () => {

                this.itemEvents();
                this.loading = false;

            });

        }
    };
   xhr.open('GET', this.iurl+'/objektliste/item/'+id+'?'+data);

    console.log(this.iurl+'/objektliste/item/'+id+'?'+data);
    xhr.send();

}
</code>```

Body:
I am integrating a javascript code(with file name) in a div of customer Website page. This javascript code is creating many items with short detail in a div. when we click for more detail of a perticular item then it displays the more detail in the same div without changing the Url. I want that when we click on more detail then it should also add the id of item in the Url.

Customer add below line of code in their div.In Objektlist.js i have defined click event for more details. Here I am using 'XMLHttpRequest' for fetching the more details of the item.

I am using PHP, Javascript, Ajax

Url of Customer Website is when it is showing all the items with less detail and more item.
https://www.example.de/offers/

I want when anyone click on more detail then Url should change like below:
https://www.example.de/offers/#item-123    or https://www.example.de/offers?item=123

This is my more detail button html code

id }}" style="margin-top: 10px;margin-bottom:10px;">More detail

Here is my main code for getItem:

getItem(id){

    if(this.loading){ return; }

    this.loading = true;
    this.container.classList.toggle('fade-out');

    var data = [
        'objektliste=' + this.objektliste_id,
    ];
    data = encodeURI(data.join('&'));

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = () => {
        if (xhr.readyState === 4){

            this.container.innerHTML = xhr.responseText;
            console.log(this.container.innerHTML);
            this.container.classList.toggle('fade-out');

            this.addScripts([
                //'//google.com/recaptcha/api.js?render=6LdQN5wUAAAAAL7skFoMkYv5_9fg1WCrztd_ALRc',
                //JR: '//maps.google.com/maps/api/js?key=AIzaSyAoux8Z8eQWOs06n4hJacb_IATFKOQ62oo&libraries=drawing',
                //'//anbieter.ivd24immobilien.de/js/jquery-1.8.0.js',
                'https://code.jquery.com/jquery-3.3.1.min.js',
                'https://code.jquery.com/jquery-migrate-1.4.1.min.js',
                //'https://www.ivd24immobilien.de/wp-content/themes/ivd24/js/jquery-migrate-1.4.1.minimmo1.js',
                //'//cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js',
                'https://npmcdn.com/tether@1.2.4/dist/js/tether.min.js',

                this.iurl+'/js/objektlisten/item.js',
            ], () => {

                this.itemEvents();
                this.loading = false;

            });

        }
    };
   xhr.open('GET', this.iurl+'/objektliste/item/'+id+'?'+data);

    console.log(this.iurl+'/objektliste/item/'+id+'?'+data);
    xhr.send();

}


问:
How to set a Work Manager to listen to an unlock screen event (android.intent.action.USER_PRESENT)
I'm trying to set up an Android Work Manager in Java which is triggered every Time the screen gets unlocked.

With Android <= 8 it was possible to use the Broadcast service and define the triggers in the manifest.xml like shown here

However, I could not find any information on how to listen to such events like screen unlocked (android.intent.action.USER_PRESENT) with the "new" Work Manager.


问:
Automatically detect unused code and exclude it from wheel build
I have a large(ish) python library that does a lot of inter-related stuff (training some neural networks, setting up datasets, testing, evaluation, running inference on the networks, etc.). I want to build an extremely lightweight cut-down bare bones wheel package, which would only allow running of the inference and a few related things, all in all I only need to call maybe 5 different functions. This would have fewer deps and other benefits (not the least a faster start time).

I started doing this by hand, by specifying only the necessary packages and removing the no-longer needed imports via sed in my build script. But this isn't very scalable at all, as soon as I make any changes to the files affected, the build script will need to be updated.

I've been reading up on tools such as Vulture, which would do static code analysis and show me dead code branches, but it's not quite what I need. For one, there are many CLI scripts which are not used (and which won't be discovered), and for the other the results are not immediately usable, I would still need to build something around it.

I cannot believe there isn't a tool to do this. What I'm after is specifying a bunch of functions (as imports?) and getting out the minimum amount of code that is needed to run those successfully. Of course I could build something of that sort, but that feels like reinventing the wheel. Is there a tool out there which I could either just use, or possibly bend to my needs? Thanks!


问:
Window as dialog from .axaml and .axaml.cs files
i'm sorry if it's stupid or "noob" question, i'm just started to learning OOP with C# and Avalonia. So I have problem with showing window as dialog. I want to show windows that i created (LogInWindow.axaml/.cs) but all i get is empty window that is not that one i want to show up. I looked Windows in Avalonia documentation and example from Music store, but still I don't know how to make it work.

I have two new files:
LogInWindow.axaml
LogInWindow.axaml.cs

Here is code i have in my MainWindow.axaml.cs:

```<code>
public void LogOut_Click(object sender, RoutedEventArgs e)
    {
        var ownerWindow = this;
        var logInWindow = new Window();
        logInWindow.ShowDialog(ownerWindow);
    }

</code>```

Also I'm geting error in my LogInWindow.axaml.cs

The name "InitializeComponent" does not exist in the current context
Problem with InitializeComponent

Body:
i'm sorry if it's stupid or "noob" question, i'm just started to learning OOP with C# and Avalonia. So I have problem with showing window as dialog. I want to show windows that i created (LogInWindow.axaml/.cs) but all i get is empty window that is not that one i want to show up. I looked Windows in Avalonia documentation and example from Music store, but still I don't know how to make it work.

I have two new files:
LogInWindow.axaml
LogInWindow.axaml.cs

Here is code i have in my MainWindow.axaml.cs:

public void LogOut_Click(object sender, RoutedEventArgs e)
    {
        var ownerWindow = this;
        var logInWindow = new Window();
        logInWindow.ShowDialog(ownerWindow);
    }

Also I'm geting error in my LogInWindow.axaml.cs

The name "InitializeComponent" does not exist in the current context
Problem with InitializeComponent


问:
How to find last connected date of each user in PostgreSQL
is there a way to find out when was the each users last(date/time) connected to PostgreSQL.

my requirement is to remove the users who did not connected to PostgreSQL server for longer period.

I updated below things in the

```<code>postgresql.conf
</code>```

file

```<code>log_connections = on
log_disconnections = on
</code>```

and checked  with below query

```<code>select * from pg_stat_activity
</code>```

it is giving information about current connecting users, which is not what I want.

Body:
is there a way to find out when was the each users last(date/time) connected to PostgreSQL.

my requirement is to remove the users who did not connected to PostgreSQL server for longer period.

I updated below things in the

postgresql.conf

file

log_connections = on
log_disconnections = on

and checked  with below query

select * from pg_stat_activity

it is giving information about current connecting users, which is not what I want.


问:
How to display the options of a ChoicePrompt again after returning false in its custom validator function
When I verify that the user's response is not on the list of options I have, I want the question with the options to be displayed again as the first time.</p>
```<code>var choices = CountryChoices.Choises;
var userChoice = promptContext.Context.Activity.Text;

if (choices.Contains(userChoice))
{
    return true;
}
else
{
    await promptContext.Context.SendActivityAsync(MessageFactory.Text($"Por favor ingrese una opción válida."), cancellationToken);

    //Here we show the choiceprompt again.

    return false;
}
</code>```

Body:
When I verify that the user's response is not on the list of options I have, I want the question with the options to be displayed again as the first time.

var choices = CountryChoices.Choises;
var userChoice = promptContext.Context.Activity.Text;

if (choices.Contains(userChoice))
{
    return true;
}
else
{
    await promptContext.Context.SendActivityAsync(MessageFactory.Text($"Por favor ingrese una opción válida."), cancellationToken);

    //Here we show the choiceprompt again.

    return false;
}


问:
How do I detect a discord message as a user and not a bot
I am trying to code a python script for 'Number Chain' channels in common discord servers. I have imported pynput for the typing but now I need a detection system.

I was thinking of using a delay like 2 seconds, but I realized that someone could type faster and it would corrupt the chain. This is the code I currently have.

```<code>#import mouse and keyboard
from pynput.mouse import Button as MouseButton, Controller
mouse = Controller()

from pynput.keyboard import Key, Controller as KeyboardController
keyboard = KeyboardController()

from time import sleep

</code>```

I am going to work on the calculating part but can someone help with the detection?

Body:
I am trying to code a python script for 'Number Chain' channels in common discord servers. I have imported pynput for the typing but now I need a detection system.

I was thinking of using a delay like 2 seconds, but I realized that someone could type faster and it would corrupt the chain. This is the code I currently have.

#import mouse and keyboard
from pynput.mouse import Button as MouseButton, Controller
mouse = Controller()

from pynput.keyboard import Key, Controller as KeyboardController
keyboard = KeyboardController()

from time import sleep

I am going to work on the calculating part but can someone help with the detection?


问:
Problem to run NCA package at google colab
until last week it was possible to run NCA package at google colab with R runtime machine.

Now, it is not possible, and this message appear.

Thanks in advance for tips to overcome this.
Edmundo


问:
Questions on use of CCDT to connect to IBM MQ
I am looking for HA/LB solution for my java (spring-boot) application doing pub/sub messages through IBM MQ and have following questions on CCDT

given a queue manager cluster of 2 QMs, naming QM1 and QM2, can my application use CCDT to achieve some kind of HA? that is defined both QM1 & QM2 in CCDT and if QM1 fails, application will automatically switch to QM2. the tricky part is QM1/2 have different names and in application property you can specify only one QM name. I found a document about Queue manager groups, is this right way to go?

how to achieve LB? say there is two instances of the application, and they are able to connect to different QMs by default

I understand that JSON format CCDT was introduced in IBM MQ after version 9.1.2. Since the CCDT file is for client-side usage, I wonder if I can use JSON format CCDT in a java application with latest version MQ library (v9.3.0) to connect to an earlier version of IBM MQ server (v9.1.0). provided that latest version MQ library has no problem connecting to v9.1.0 with connection properties set


问:
How to send a POST request in JS in the same way that Python Requests Session does so with an auth tuple
I am currently hitting an API with some Python code using the requests module where I open a session. The only way to hit some resources is to be authenticated so I create an auth tuple with the my username and password. The code to get an idea of what all is being done is below.

```<code>Class Requester():
    def __init__(self, auth, noverify, user, pass):
        self.auth = auth
        self.noverify = noverify
        self.session = requests.Session()
        if self.auth:
            self.session.auth = (user, pass)

    def post(self, ...):
        r = self.session.post(self.urlbase + endpoint, data=args, files=files, verify=False)

</code>```

This works successfully for any endpoint I've used.

Now, I need to do the same in JS. I have tried hitting endpoints that don't require authentication with both JQuery AJAX requests and with fetch. Both seem to work fine. Unfortunately, I have been unable to hit any endpoints that require auth to work. I suspect that the Python Session object is doing something with that tuple that I don't understand. Is there a way to produce the same request via JS?

Body:
I am currently hitting an API with some Python code using the requests module where I open a session. The only way to hit some resources is to be authenticated so I create an auth tuple with the my username and password. The code to get an idea of what all is being done is below.

Class Requester():
    def __init__(self, auth, noverify, user, pass):
        self.auth = auth
        self.noverify = noverify
        self.session = requests.Session()
        if self.auth:
            self.session.auth = (user, pass)

    def post(self, ...):
        r = self.session.post(self.urlbase + endpoint, data=args, files=files, verify=False)

This works successfully for any endpoint I've used.

Now, I need to do the same in JS. I have tried hitting endpoints that don't require authentication with both JQuery AJAX requests and with fetch. Both seem to work fine. Unfortunately, I have been unable to hit any endpoints that require auth to work. I suspect that the Python Session object is doing something with that tuple that I don't understand. Is there a way to produce the same request via JS?


问:
"ImportError: DLL load failed: %1 is not a valid Win32 application." but both Python and matplotlib are 64 bit
I am trying to run the same code on my new PC (Windows 11). I installed Python 2.7 and matplotlib in both 64 bit but I still get "ImportError: DLL load failed: %1 is not a valid Win32 application."

I know this has been asked many times (e.g., here, here, here, here, here, here) and after reading all of these previously-asked posts, it seems you get this error when Python and the module bit do not match (e.g., Python in 32 bit and module in 64 bit, and vice versa). That is why I made sure that both are running in 64 bit. I restarted my PC, and I even installed pywin32 in 64 bit but that did not fix this issue.

My environment and versions
Windows 11 Pro 64 bit
Python 2.7.16 (v2.7.16:413a49145e, Mar  4 2019, 01:37:19) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
matplotlib: 2.2.5
pywin32: 228

Codes when the error occurs in PowerShell
import csv, os, os.path, pdb
import matplotlib.pyplot as plt

I also get the same error when I try to import _tkinter (based on another question)

I have been trying to figure this out for days now and I would appreciate it if anybody could suggest what else I could do to make it work. Thanks!


问:
How to delete a specific product from a basket that has a unique key via axios.delete
I have not worked with the API before, I have a task to remove a specific product from the API that I clicked in the Vue component. And I also have a temporary shopping cart for users in localStorage. I was told that the axios request should contain the ProductID(the product I want to delete) and the user Access Key (temporary shopping cart for the user)

My request in actions is:

```<code>DELETE_PRODUCT({commit} , productId){
return axios.delete('url' , {productId} , {params: {userAccessKey: this.state.userAccessKey}})
.then(() => {
   commit('CONSOLE_LOG')
})

}
</code>```

Since I haven't worked with requests before, I thought I would pass the data for deletion directly in the form of a post or put request. But it didn't work, it gave an error of 400.
And the instructions say that if it throws a 400 error, it means either the product ID is incorrect or the user's access key is incorrect.I swapped params and ProductID in axios.delete and then it gives out. In devtools network, I see only 1 error, it's either "The product was not found in the basket" or pass the userAccessKey incorrectly.
The instructions also said that first, before deleting the product, you need to check if the product exists in the API basket

Body:
I have not worked with the API before, I have a task to remove a specific product from the API that I clicked in the Vue component. And I also have a temporary shopping cart for users in localStorage. I was told that the axios request should contain the ProductID(the product I want to delete) and the user Access Key (temporary shopping cart for the user)

My request in actions is:

DELETE_PRODUCT({commit} , productId){
return axios.delete('url' , {productId} , {params: {userAccessKey: this.state.userAccessKey}})
.then(() => {
   commit('CONSOLE_LOG')
})

}

Since I haven't worked with requests before, I thought I would pass the data for deletion directly in the form of a post or put request. But it didn't work, it gave an error of 400.
And the instructions say that if it throws a 400 error, it means either the product ID is incorrect or the user's access key is incorrect.I swapped params and ProductID in axios.delete and then it gives out. In devtools network, I see only 1 error, it's either "The product was not found in the basket" or pass the userAccessKey incorrectly.
The instructions also said that first, before deleting the product, you need to check if the product exists in the API basket


问:
Eloquent ORM filter multiple level relationship
I have a school system where I defined multiple models:

Student

Subscription

Grade

Subject

Score

Those are defined with the following relationship:

Subject belongsTo Grade

Grade hasMany Subscription

Subscription belongsTo Student and Grade

Score belongsTo Student and Subject

Student hasMany Score <- I need to filter this for just one Subject.

Using a Subject model I need to find the Students (already done using Subject->Grade->Subscription relationship) and attach the Score for the current Subject.

Currently I can get all the Scores for the Student using the Student hasMany Score relationship.

How can I filter that relationship to get only the Scores for a single Subject?


问:
Transfer tool Error no API token? at /usr/local/cpanel/Whostmgr/Transfers/Utils.pm line 735
no API token? at /usr/local/cpanel/Whostmgr/Transfers/Utils.pm line 735.

I was trying to migrate cPanel accounts from one server to another using transfer tool when I encountered the above-mentioned issue. No database is being migrated

cPanel verison: 106.0.11
phpMyAdmin version: 5.7
Operating System: CloudLinux but previously was CentOs7

I tried to upgrade cPanel and phpMyAdmin to match the target server, but it would not work.


问:
How can I render HTML-file content to specific tag/word into a template.docx file (word replacement)?
How can I copy the content of an HTML file (data_1.html") to a specific
location in a pre-made "template.docx" and then save it as "output.docx" with python?

I know, that it is possible with this simple Code to convert html to docx perfectly included formats like (bold,underline,italic):

```<code>from htmldocx import HtmlToDocx

new_parser = HtmlToDocx()
new_parser.parse_html_file(input_html_file_path, output_docx_file_path)
</code>```

But somehow I'm not able to replace a word/tag with the content, like it is kind of possible with
"python-docx-template". There it is easy to define a word, that replaces specific text within a template like here:

```<code>from docxtpl import DocxTemplate

doc = DocxTemplate("my_word_template.docx")
context = { 'company_name' : "World company" }
doc.render(context)
doc.save("generated_doc.docx")
</code>```

But how is it possible to define the content of a HTML-file that replaces the word in a "template.docx" file?

When I try it like this...:

```<code>from docxtpl import DocxTemplate

doc = DocxTemplate("template.docx")
data1 = open("data_1.html", "r")
context = { 'MONTAG' : data1 }
doc.render(context)
doc.save("output.docx")
</code>```

...and try to open the "output.docx", I get an error like "Error opening file in Word"

Here is an example of how I would like it to work:

html_to_docx_example

Body:
How can I copy the content of an HTML file (data_1.html") to a specific
location in a pre-made "template.docx" and then save it as "output.docx" with python?

I know, that it is possible with this simple Code to convert html to docx perfectly included formats like (bold,underline,italic):

from htmldocx import HtmlToDocx

new_parser = HtmlToDocx()
new_parser.parse_html_file(input_html_file_path, output_docx_file_path)

But somehow I'm not able to replace a word/tag with the content, like it is kind of possible with
"python-docx-template". There it is easy to define a word, that replaces specific text within a template like here:

from docxtpl import DocxTemplate

doc = DocxTemplate("my_word_template.docx")
context = { 'company_name' : "World company" }
doc.render(context)
doc.save("generated_doc.docx")

But how is it possible to define the content of a HTML-file that replaces the word in a "template.docx" file?

When I try it like this...:

from docxtpl import DocxTemplate

doc = DocxTemplate("template.docx")
data1 = open("data_1.html", "r")
context = { 'MONTAG' : data1 }
doc.render(context)
doc.save("output.docx")

...and try to open the "output.docx", I get an error like "Error opening file in Word"

Here is an example of how I would like it to work:

html_to_docx_example


问:
"RCTScrollContentView" was not found in the UIManager
```<code>Invariant Violation: requireNativeComponent: "RCTScrollContentView" was not found in the UIManager.

This error is located at:
    in RCTScrollContentView (created by ScrollView)
    in RCTScrollView (created by ScrollView)
    in ScrollView (created by ScrollView)
    in ScrollView (created by VirtualizedList)
    in VirtualizedListContextProvider (created by VirtualizedList)
    in VirtualizedList (created by FlatList)
    in FlatList (created by chatBot)
    in RCTView (created by View)
    in View (created by chatBot)
    in RCTView (created by View)
    in View (created by chatBot)
    in chatBot (created by App)
    in RCTView (created by View)
    in View (created by App)
    in App (created by withDevTools(App))
    in withDevTools(App)
    in RCTView (created by View)
    in View (created by AppContainer)
    in RCTView (created by View)
    in View (created by AppContainer)
    in AppContainer
    in main(RootComponent)
at node_modules\react-native\Libraries\Core\ExceptionsManager.js:null in reportException
at node_modules\react-native\Libraries\Core\ExceptionsManager.js:null in handleException
at node_modules\react-native\Libraries\Core\setUpErrorHandling.js:null in handleError
at node_modules\expo\build\errors\ExpoErrorManager.js:null in errorHandler
at node_modules\expo\build\errors\ExpoErrorManager.js:null in <anonymous>
at node_modules\@react-native\polyfills\error-guard.js:null in ErrorUtils.reportFatalError
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in __guard
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in callFunctionReturnFlushedQueue

Invariant Violation: requireNativeComponent: "RCTScrollContentView" was not found in the UIManager.

This error is located at:
    in RCTScrollContentView (created by ScrollView)
    in RCTScrollView (created by ScrollView)
    in ScrollView (created by ScrollView)
    in ScrollView (created by VirtualizedList)
    in VirtualizedListContextProvider (created by VirtualizedList)
    in VirtualizedList (created by FlatList)
    in FlatList (created by chatBot)
    in RCTView (created by View)
    in View (created by chatBot)
    in RCTView (created by View)
    in View (created by chatBot)
    in chatBot (created by App)
    in RCTView (created by View)
    in View (created by App)
    in App (created by withDevTools(App))
    in withDevTools(App)
    in RCTView (created by View)
    in View (created by AppContainer)
    in RCTView (created by View)
    in View (created by AppContainer)
    in AppContainer
    in main(RootComponent)
at node_modules\react-native\Libraries\Core\ExceptionsManager.js:null in reportException
at node_modules\react-native\Libraries\Core\ExceptionsManager.js:null in handleException
at node_modules\react-native\Libraries\Core\ReactFiberErrorDialog.js:null in showErrorDialog
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:null in logCapturedError
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:null in update.callback
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:null in callCallback
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:null in commitUpdateQueue
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:null in _callTimer
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:null in callTimers
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in __callFunction
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in __guard$argument_0
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in __guard
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in callFunctionReturnFlushedQueue
</code>```

I tried to create a list view for a chat application. But it gonna this error after adding FlatList component. without FlatList, this program works fine. I'm run this program on android device using expo. I'm new to programming and please help me.

Here is my code

```<code>import React, {useState} from "react";
import {
    FlatList,
    View,
    TouchableOpacity,
    Text,
    TextInput
} from "react-native";
import Msg from "./msg";
import data from "./data";
import styles from "./styles";

let chats = [];

const chatBot = () => {

    const [chatList, setChatList] = useState([]);
    const [msg, setMsg] = useState('')
    return (
        <View>
            <View>
                <FlatList style={{height: '90%'}}
                          data={chatList}
                          inverted={true}
                          keyExtractor={(_, index) => index.toString()}
                          renderItem={({item}) => (
                              <Msg
                                  incomeMsg={item.incomeMsg}
                                  msg={msg}
                                  sentMsg={item.sentMsg}
                              />
                          )}
                />
            </View>
            <View style={styles.inputOuter}>
                <TextInput
                    style={styles.inputBody}
                    value={msg}
                    placeholder="Type a message..."
                    onChangeText={val => setMsg(val)}
                />

                <TouchableOpacity style={[styles.sendBtn, {backgroundColor: msg ? '#3498db' : '#95a5a6'}]}
                                  disabled={!msg}>
                    <Text style={styles.sendBtnText}>Send</Text>
                </TouchableOpacity>
            </View>
        </View>

    )
}

export default chatBot;
</code>```

msg.js is here

```<code>import React, {Fragment} from "react";
import {
    Text,
    View
} from "react-native";
import styles from "./styles";

const Msg=({incomeMsg,sentMsg,msg})=>{
    return(
        <Fragment>
            {/*Incoming msg*/}
            {
                incomeMsg && (<View style={styles.incomeMsg}>
                    <Text style={styles.incomeMsgText}>{msg}</Text>
                </View>)
            }

            {/*Sent msg*/}
            {
                sentMsg && (<View style={styles.sentMsg}>
                    <Text style={styles.sentMsgText}>{msg}</Text>
                </View>)
            }

        </Fragment>
    )
}

export default Msg;
</code>```

styles are here

```<code>import {
    StyleSheet,Platform
} from "react-native";

const styles = StyleSheet.create({
    container:{
        flex:1,
        marginTop:Platform.OS='ios'? 25 : 30,
        padding:5
    },
    incomeMsg:{
        maxWidth:'70%',
        backgroundColor:'#2ecc71',
        borderRadius:10,
        alignSelf:'flex-start',
        padding:5
    },
    incomeMsgText:{
        color:'white',
        fontSize:16
    },
    sentMsg:{
        maxWidth:'70%',
        backgroundColor:'#3498db',
        borderRadius:10,
        alignSelf:'flex-end',
        padding:5
    },
    sentMsgText:{
        color:'white',
        fontSize:16
    },
    inputOuter:{
        flexDirection:'row',
        borderColor:'red',
        borderWidth:1,
        flex:1
    },
    inputBody:{
        width:'80%',
        borderRadius:20,
        borderColor:'red',
        borderWidth:1,
        padding:10
    },
    sendBtn:{
        alignItems:'center',
        justifyContent:'center',
        borderRadius:100,
        padding:5,
        flex:1
    },
    sendBtnText:{
        color:'#ffffff',
        fontSize:16,
        textAlign:'center'
    }
});

export default styles;
</code>```

Body:
Invariant Violation: requireNativeComponent: "RCTScrollContentView" was not found in the UIManager.

This error is located at:
    in RCTScrollContentView (created by ScrollView)
    in RCTScrollView (created by ScrollView)
    in ScrollView (created by ScrollView)
    in ScrollView (created by VirtualizedList)
    in VirtualizedListContextProvider (created by VirtualizedList)
    in VirtualizedList (created by FlatList)
    in FlatList (created by chatBot)
    in RCTView (created by View)
    in View (created by chatBot)
    in RCTView (created by View)
    in View (created by chatBot)
    in chatBot (created by App)
    in RCTView (created by View)
    in View (created by App)
    in App (created by withDevTools(App))
    in withDevTools(App)
    in RCTView (created by View)
    in View (created by AppContainer)
    in RCTView (created by View)
    in View (created by AppContainer)
    in AppContainer
    in main(RootComponent)
at node_modules\react-native\Libraries\Core\ExceptionsManager.js:null in reportException
at node_modules\react-native\Libraries\Core\ExceptionsManager.js:null in handleException
at node_modules\react-native\Libraries\Core\setUpErrorHandling.js:null in handleError
at node_modules\expo\build\errors\ExpoErrorManager.js:null in errorHandler
at node_modules\expo\build\errors\ExpoErrorManager.js:null in <anonymous>
at node_modules\@react-native\polyfills\error-guard.js:null in ErrorUtils.reportFatalError
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in __guard
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in callFunctionReturnFlushedQueue

Invariant Violation: requireNativeComponent: "RCTScrollContentView" was not found in the UIManager.

This error is located at:
    in RCTScrollContentView (created by ScrollView)
    in RCTScrollView (created by ScrollView)
    in ScrollView (created by ScrollView)
    in ScrollView (created by VirtualizedList)
    in VirtualizedListContextProvider (created by VirtualizedList)
    in VirtualizedList (created by FlatList)
    in FlatList (created by chatBot)
    in RCTView (created by View)
    in View (created by chatBot)
    in RCTView (created by View)
    in View (created by chatBot)
    in chatBot (created by App)
    in RCTView (created by View)
    in View (created by App)
    in App (created by withDevTools(App))
    in withDevTools(App)
    in RCTView (created by View)
    in View (created by AppContainer)
    in RCTView (created by View)
    in View (created by AppContainer)
    in AppContainer
    in main(RootComponent)
at node_modules\react-native\Libraries\Core\ExceptionsManager.js:null in reportException
at node_modules\react-native\Libraries\Core\ExceptionsManager.js:null in handleException
at node_modules\react-native\Libraries\Core\ReactFiberErrorDialog.js:null in showErrorDialog
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:null in logCapturedError
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:null in update.callback
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:null in callCallback
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:null in commitUpdateQueue
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:null in _callTimer
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:null in callTimers
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in __callFunction
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in __guard$argument_0
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in __guard
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in callFunctionReturnFlushedQueue

I tried to create a list view for a chat application. But it gonna this error after adding FlatList component. without FlatList, this program works fine. I'm run this program on android device using expo. I'm new to programming and please help me.

Here is my code

import React, {useState} from "react";
import {
    FlatList,
    View,
    TouchableOpacity,
    Text,
    TextInput
} from "react-native";
import Msg from "./msg";
import data from "./data";
import styles from "./styles";

let chats = [];

const chatBot = () => {

    const [chatList, setChatList] = useState([]);
    const [msg, setMsg] = useState('')
    return (
        <View>
            <View>
                <FlatList style={{height: '90%'}}
                          data={chatList}
                          inverted={true}
                          keyExtractor={(_, index) => index.toString()}
                          renderItem={({item}) => (
                              <Msg
                                  incomeMsg={item.incomeMsg}
                                  msg={msg}
                                  sentMsg={item.sentMsg}
                              />
                          )}
                />
            </View>
            <View style={styles.inputOuter}>
                <TextInput
                    style={styles.inputBody}
                    value={msg}
                    placeholder="Type a message..."
                    onChangeText={val => setMsg(val)}
                />

                <TouchableOpacity style={[styles.sendBtn, {backgroundColor: msg ? '#3498db' : '#95a5a6'}]}
                                  disabled={!msg}>
                    <Text style={styles.sendBtnText}>Send</Text>
                </TouchableOpacity>
            </View>
        </View>

    )
}

export default chatBot;

msg.js is here

import React, {Fragment} from "react";
import {
    Text,
    View
} from "react-native";
import styles from "./styles";

const Msg=({incomeMsg,sentMsg,msg})=>{
    return(
        <Fragment>
            {/*Incoming msg*/}
            {
                incomeMsg && (<View style={styles.incomeMsg}>
                    <Text style={styles.incomeMsgText}>{msg}</Text>
                </View>)
            }

            {/*Sent msg*/}
            {
                sentMsg && (<View style={styles.sentMsg}>
                    <Text style={styles.sentMsgText}>{msg}</Text>
                </View>)
            }

        </Fragment>
    )
}

export default Msg;

styles are here

import {
    StyleSheet,Platform
} from "react-native";

const styles = StyleSheet.create({
    container:{
        flex:1,
        marginTop:Platform.OS='ios'? 25 : 30,
        padding:5
    },
    incomeMsg:{
        maxWidth:'70%',
        backgroundColor:'#2ecc71',
        borderRadius:10,
        alignSelf:'flex-start',
        padding:5
    },
    incomeMsgText:{
        color:'white',
        fontSize:16
    },
    sentMsg:{
        maxWidth:'70%',
        backgroundColor:'#3498db',
        borderRadius:10,
        alignSelf:'flex-end',
        padding:5
    },
    sentMsgText:{
        color:'white',
        fontSize:16
    },
    inputOuter:{
        flexDirection:'row',
        borderColor:'red',
        borderWidth:1,
        flex:1
    },
    inputBody:{
        width:'80%',
        borderRadius:20,
        borderColor:'red',
        borderWidth:1,
        padding:10
    },
    sendBtn:{
        alignItems:'center',
        justifyContent:'center',
        borderRadius:100,
        padding:5,
        flex:1
    },
    sendBtnText:{
        color:'#ffffff',
        fontSize:16,
        textAlign:'center'
    }
});

export default styles;


问:
Web iOS Scroll Bug on Fast Scroll
I'm getting a weird UI bug on web on iOS across all three browsers I've tested (Chrome, Firefox, Safari). I'm on an iPhone 14. I have a number of cards that scroll vertically, and I have overflow-x-hidden overscroll-y-none on the body. I'm using Tailwind and NextJS.

When I quickly scroll up and down, I eventually get to this situation:

In the inspector on Safari, I've highlighted the card as the blue box. The blue box is where the card is supposed to be, according to the information in the DOM (and where I want it). Instead the card is showing up tiny and to the left, as you can see. Nothing in the DOM has changed, AFAICT. With a refresh, everything looks normal again.

You can see this behavior for yourself at gregliest.com. On an iPhone, scroll up and down quickly until you see this situation.

Does anyone know what's going on?

Title: Web iOS Scroll Bug on Fast Scroll


问:
How to get minikube OIDC metadata?
I have deployed minikube on my local Docker. Is there a way to configure it to expose the OIDC .well-known metadata (locally)? Something like described here.</p>

Title: How to get minikube OIDC metadata?


问:
How can i show text in console
I was trying to see if I can send a message to my console but there is an error.

I have the following line of code:

```<code><script src='./js/pages/index.js" type="module"></script>
</code>```

And at that route there is a code that I want to send to my console:

```<code>console.log("hello");
</code>```

But, when I enter to my page, there is an error:

How can I resolve this error to send the message to console?

Title: How can i show text in console

Body:
I was trying to see if I can send a message to my console but there is an error.

I have the following line of code:

And at that route there is a code that I want to send to my console:

console.log("hello");

But, when I enter to my page, there is an error:

How can I resolve this error to send the message to console?


问:
How favicon is set without link tag?
In https://ziglang.org/ I see favicon on a tab but there's no link tag which defines icon in its source code. How the favicon is set then? My Brave browser somehow detects it?</p>

Title: How favicon is set without link tag?


问:
Scapy gives false data
I'm trying to create my own DNS server in python.
I created a server using sockets library -

```<code>self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.bind(('127.0.0.1', 53))
dns_req, client_addr = self.sock.recvfrom(512)
</code>```

But when I try to extract data from the packet I get false data.

So for example if I run:
dig google.com @127.0.0.1 and IP(dns_req).src I get an unknown ip 6.103.111.111 instead of 127.0.0.1 (or my local ip). The other data is corrupted too (but the requested domain).

I tried to run dns_req[IP].src but I got :

```<code>TypeError: byte indices must be integers or slices, not Packet_metaclass
</code>```

pls help me!!

Title: Scapy gives false data

Body:
I'm trying to create my own DNS server in python.
I created a server using sockets library -

self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.bind(('127.0.0.1', 53))
dns_req, client_addr = self.sock.recvfrom(512)

But when I try to extract data from the packet I get false data.

So for example if I run:
dig google.com @127.0.0.1 and IP(dns_req).src I get an unknown ip 6.103.111.111 instead of 127.0.0.1 (or my local ip). The other data is corrupted too (but the requested domain).

I tried to run dns_req[IP].src but I got :

TypeError: byte indices must be integers or slices, not Packet_metaclass

pls help me!!


问:
Creating project using platformio VScode extension taking too much time and stucks in project wizard window
I have dowloaded Platformio extension in VS code for development. I have selected the following board "ESP32 devkit v1" in IDE. When I create a project using platformio, it stuck in the project wizard window for very long time. Kindly suggest some solution for this issue?

I am trying to make a new project but in project wizard window it stuck for a very long period of time.


问:
Problems building a python function that checks if a primary key already exists
I'm trying to build a python function that, given a table name and the primary key of the table, it returns true if an entry with the same primary key already exists, otherwise it returns false

Here is my attempt:

```<code>def already_esists(tablename, pm_key) :

    myDB = mysql.connector.connect(
            host = "localhost",
            user = "user",
            passwd = "password",
            database = "myDatabase"
        )

    myCursor = myDB.cursor()

    # PM_KEY is the primary key attribute of every table for which I need to use this function
    query = "SELECT PM_KEY FROM %s WHERE PM_KEY = %s;"
    values = [tablename, pm_key]
    myCursor.execute(query, values)

    ID_already_exists = myCursor.fetchall()
    if ID_already_exists :
        logging.warning(primary_key + " Entry already exists")
        return True
    else :
        return False
</code>```

However, once called, I get the following error:

mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''table_name_example' WHERE PM_KEY = 'GELheLpr'' at line 1

GELheLpr is for example a primary key of an entry of table_name_example.

Body:
I'm trying to build a python function that, given a table name and the primary key of the table, it returns true if an entry with the same primary key already exists, otherwise it returns false

Here is my attempt:

def already_esists(tablename, pm_key) :

    myDB = mysql.connector.connect(
            host = "localhost",
            user = "user",
            passwd = "password",
            database = "myDatabase"
        )

    myCursor = myDB.cursor()

    # PM_KEY is the primary key attribute of every table for which I need to use this function
    query = "SELECT PM_KEY FROM %s WHERE PM_KEY = %s;"
    values = [tablename, pm_key]
    myCursor.execute(query, values)

    ID_already_exists = myCursor.fetchall()
    if ID_already_exists :
        logging.warning(primary_key + " Entry already exists")
        return True
    else :
        return False

However, once called, I get the following error:

mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''table_name_example' WHERE PM_KEY = 'GELheLpr'' at line 1

GELheLpr is for example a primary key of an entry of table_name_example.


问:
I want them to hover one by one
Now my code crashes when hovering over all I use to mapitem down image data. I only want one hover at a time. when hovering over What should I do?
this is my code

```<code>function ImgCard(props) {

    const [isHovered, setIsHovered] = useState(true);

    const handleMouseEnter = () => {
        setIsHovered(false);
    };

    const handleMouseLeave = () => {
        setIsHovered(true);
    };

    return (
        <div>

            <Container sx={{ pt: 5 }}>
                <Card p={5}>

                    <Container>

                            <Container>
                                <Grid>
                                    <Grid container spacing={2}>
                                            <Grid item key={item} xs={6} md={3}>
                                                <Card
                                                    sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}
                                                    style={{ color: "gray", textAlign: "center" }}
                                                >
                                                    <CardMedia

                                                        component="img"
                                                        sx={{
                                                            pt: '10.9%',

                                                        }}
                                                        image={item.src}
                                                        onMouseEnter={handleMouseEnter}
                                                        onMouseLeave={handleMouseLeave}
                                                        style={{
                                                            filter: isHovered ? 'brightness(75%)' : 'none',
                                                            transition: 'filter 0.3s ease-in-out'
                                                        }}
                                                        alt="random"
                                                    />
                                                </Card>
                                            </Grid>
</code>```

I sat down for 3 days and I really couldn't fix it. Really out of wit

Title: I want them to hover one by one

Body:
Now my code crashes when hovering over all I use to mapitem down image data. I only want one hover at a time. when hovering over What should I do?
this is my code

function ImgCard(props) {

    const [isHovered, setIsHovered] = useState(true);

    const handleMouseEnter = () => {
        setIsHovered(false);
    };

    const handleMouseLeave = () => {
        setIsHovered(true);
    };

    return (

            <Container sx={{ pt: 5 }}>
                <Card p={5}>

                    <Container>

                            <Container>
                                <Grid>
                                    <Grid container spacing={2}>
                                            <Grid item key={item} xs={6} md={3}>
                                                <Card
                                                    sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}
                                                    style={{ color: "gray", textAlign: "center" }}
                                                >
                                                    <CardMedia

                                                        component="img"
                                                        sx={{
                                                            pt: '10.9%',

                                                        }}
                                                        image={item.src}
                                                        onMouseEnter={handleMouseEnter}
                                                        onMouseLeave={handleMouseLeave}
                                                        style={{
                                                            filter: isHovered ? 'brightness(75%)' : 'none',
                                                            transition: 'filter 0.3s ease-in-out'
                                                        }}
                                                        alt="random"
                                                    />
                                                </Card>
                                            </Grid>

I sat down for 3 days and I really couldn't fix it. Really out of wit


问:
How to make links send DELETE requests?
I have this link in my view. It clears the cart (I'm developing an online store):

@Html.ActionLink("Clear", "Clear")
```

It works fine, but doesn't fit the HTTP specification. It sends a GET request that changes the current state (clears cart), and it is said in the specification that GET requests shouldn't be "changing".

There is a similar question on Stack Overflow that has an accepted answer. It suggests using Ajax.ActionLink and specifying HttpMethod = "POST" in the AjaxOptions. However, it doesn't fit because of these reasons:

I want my link to send DELETE requests (because there is already a handler for POST for deleting specific items. It receives a form.)

I don't want to use Ajax links (if possible).

Any help will be appreciated.

Title: How to make links send DELETE requests?

Body:
I have this link in my view. It clears the cart (I'm developing an online store):

@Html.ActionLink("Clear", "Clear")

It works fine, but doesn't fit the HTTP specification. It sends a GET request that changes the current state (clears cart), and it is said in the specification that GET requests shouldn't be "changing".

There is a similar question on Stack Overflow that has an accepted answer. It suggests using Ajax.ActionLink and specifying HttpMethod = "POST" in the AjaxOptions. However, it doesn't fit because of these reasons:

I want my link to send DELETE requests (because there is already a handler for POST for deleting specific items. It receives a form.)

I don't want to use Ajax links (if possible).

Any help will be appreciated.


问:
How to use usbprinter package in golang?
Currently, the usb pos printer is connected via usb. I tried various ways to save the data output by the printer to the pc, but all failed.
As a last method, I thought of configuring a virtual printer on the pc, saving the data transmitted to the virtual printer to the pc, and then outputting the saved data again.

First, I want to set up a virtual printer.

I found a suitable package for this, but I can't import it.
https://pkg.go.dev/chromium.googlesource.com/chromiumos/platform/tast-tests.git/src/chromiumos/tast/local/printing/usbprinter#section-documentation

I ran the below command in the console, but I can't import the package normally.

```<code>-MacBookPro printer % go get -u chromium.googlesource.com/chromiumos/platform/tast-tests
go: unrecognized import path "chromium.googlesource.com/chromiumos/platform/tast-tests": parse https://chromium.googlesource.com/chromiumos/platform/tast-tests?go-get=1: no go-import meta tags ()
</code>```

Since I'm a beginner in golang, I think the repository url is wrong, but I don't know how to use the package normally.

Can you show me a simple example of configuring a virtual printer using that package? Please.

Or, is there a tutorial on how to properly import the google git package? Please give me some advice.

```<code>-MacBookPro printer % go get -u chromium.googlesource.com/chromiumos/platform/tast-tests.git/src/chromiumos/tast/local/printing/usbprinter
chromium.googlesource.com/chromiumos/platform/tast-tests.git/src/chromiumos/tast/local/printing/usbprinter imports
        chromiumos/tast/common/testexec: package chromiumos/tast/common/testexec is not in GOROOT (/opt/homebrew/Cellar/go/1.19.3/libexec/src/chromiumos/tast/common/testexec)
chromium.googlesource.com/chromiumos/platform/tast-tests.git/src/chromiumos/tast/local/printing/usbprinter imports
        chromiumos/tast/errors: package chromiumos/tast/errors is not in GOROOT (/opt/homebrew/Cellar/go/1.19.3/libexec/src/chromiumos/tast/errors)
chromium.googlesource.com/chromiumos/platform/tast-tests.git/src/chromiumos/tast/local/printing/usbprinter imports
        chromiumos/tast/local/printing/lp: package chromiumos/tast/local/printing/lp is not in GOROOT (/opt/homebrew/Cellar/go/1.19.3/libexec/src/chromiumos/tast/local/printing/lp)
chromium.googlesource.com/chromiumos/platform/tast-tests.git/src/chromiumos/tast/local/printing/usbprinter imports
        chromiumos/tast/testing: package chromiumos/tast/testing is not in GOROOT (/opt/homebrew/Cellar/go/1.19.3/libexec/src/chromiumos/tast/testing)
</code>```

I checked the comments and tried to import the package like below, but it returns an error, is there something wrong with the package??

It seems that the manual confirmed that golang does not require path-related settings since version 1.13. What part can I check to solve this problem?

Body:
Currently, the usb pos printer is connected via usb. I tried various ways to save the data output by the printer to the pc, but all failed.
As a last method, I thought of configuring a virtual printer on the pc, saving the data transmitted to the virtual printer to the pc, and then outputting the saved data again.

First, I want to set up a virtual printer.

I found a suitable package for this, but I can't import it.
https://pkg.go.dev/chromium.googlesource.com/chromiumos/platform/tast-tests.git/src/chromiumos/tast/local/printing/usbprinter#section-documentation

I ran the below command in the console, but I can't import the package normally.

-MacBookPro printer % go get -u chromium.googlesource.com/chromiumos/platform/tast-tests
go: unrecognized import path "chromium.googlesource.com/chromiumos/platform/tast-tests": parse https://chromium.googlesource.com/chromiumos/platform/tast-tests?go-get=1: no go-import meta tags ()

Since I'm a beginner in golang, I think the repository url is wrong, but I don't know how to use the package normally.

Can you show me a simple example of configuring a virtual printer using that package? Please.

Or, is there a tutorial on how to properly import the google git package? Please give me some advice.

-MacBookPro printer % go get -u chromium.googlesource.com/chromiumos/platform/tast-tests.git/src/chromiumos/tast/local/printing/usbprinter
chromium.googlesource.com/chromiumos/platform/tast-tests.git/src/chromiumos/tast/local/printing/usbprinter imports
        chromiumos/tast/common/testexec: package chromiumos/tast/common/testexec is not in GOROOT (/opt/homebrew/Cellar/go/1.19.3/libexec/src/chromiumos/tast/common/testexec)
chromium.googlesource.com/chromiumos/platform/tast-tests.git/src/chromiumos/tast/local/printing/usbprinter imports
        chromiumos/tast/errors: package chromiumos/tast/errors is not in GOROOT (/opt/homebrew/Cellar/go/1.19.3/libexec/src/chromiumos/tast/errors)
chromium.googlesource.com/chromiumos/platform/tast-tests.git/src/chromiumos/tast/local/printing/usbprinter imports
        chromiumos/tast/local/printing/lp: package chromiumos/tast/local/printing/lp is not in GOROOT (/opt/homebrew/Cellar/go/1.19.3/libexec/src/chromiumos/tast/local/printing/lp)
chromium.googlesource.com/chromiumos/platform/tast-tests.git/src/chromiumos/tast/local/printing/usbprinter imports
        chromiumos/tast/testing: package chromiumos/tast/testing is not in GOROOT (/opt/homebrew/Cellar/go/1.19.3/libexec/src/chromiumos/tast/testing)

I checked the comments and tried to import the package like below, but it returns an error, is there something wrong with the package??

It seems that the manual confirmed that golang does not require path-related settings since version 1.13. What part can I check to solve this problem?


问:
CNN-LSTM crashes a memory
I'm working on a project in deep learning  ,the project is a sketch to code (convert handwriting drawing on paper to html code)
we make CNN and LSTM  by Pytorch library in python and we run the project on google colab
That's all code and our work
https://colab.research.google.com/drive/1-E6By5qVXY1rHIH_KpndEtFjMJbPRR_8?usp=sharing

When I was training the network the memory get full and crash (memory up to 12 GB)
And I never know why; The data is not that big

Our dataset have only about 800 samples and
Batch size is 10 only
and input is photos of size 500 x 500,
Why?
what is the solution ?

Title: CNN-LSTM crashes a memory


问:
Auth Interceptor is doing a JWT Refresh request loop
my request to refresh the token is doing a loop without any stop. So there are a lot of requests that lead to a 401, because the refresh token is not valid anymore. I thought that it runs logout, but it seems like its not working.

```<code>@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  backendBaseUrl = environment.backendBaseUrl
  constructor(private authService: AuthService) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if(req.url.includes(this.backendBaseUrl)) {
    const authToken = this.authService.getToken();
    let authreq = this.addAuthHeader(req, authToken)
    return next.handle(authreq).pipe(
      catchError((error: HttpErrorResponse) => {
        if (error.status == 401 && this.authService.getRefreshToken() != "") {
          return this.refreshToken(req, next)
        }
        return throwError(error)
      }));
    } else {
      return next.handle(req)
    }
  }

  addAuthHeader(req: HttpRequest<any>, authToken: string) {
    return req.clone({
      setHeaders: {
        Authorization: "Bearer " + authToken
      }
    });
  }

  refreshToken(req: HttpRequest<any>, next: HttpHandler) {
    return this.authService.refreshTokenWithRefresh().pipe(
      switchMap((response: any) => {
        this.authService.saveJWTToken(response.access)
        return next.handle(this.addAuthHeader(req, response.access))
      }),
      catchError((error) => {
        this.authService.doLogout()
        return throwError(error)
      })
    )
  }
}
</code>```

Body:
my request to refresh the token is doing a loop without any stop. So there are a lot of requests that lead to a 401, because the refresh token is not valid anymore. I thought that it runs logout, but it seems like its not working.

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  backendBaseUrl = environment.backendBaseUrl
  constructor(private authService: AuthService) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if(req.url.includes(this.backendBaseUrl)) {
    const authToken = this.authService.getToken();
    let authreq = this.addAuthHeader(req, authToken)
    return next.handle(authreq).pipe(
      catchError((error: HttpErrorResponse) => {
        if (error.status == 401 && this.authService.getRefreshToken() != "") {
          return this.refreshToken(req, next)
        }
        return throwError(error)
      }));
    } else {
      return next.handle(req)
    }
  }

  addAuthHeader(req: HttpRequest<any>, authToken: string) {
    return req.clone({
      setHeaders: {
        Authorization: "Bearer " + authToken
      }
    });
  }

  refreshToken(req: HttpRequest<any>, next: HttpHandler) {
    return this.authService.refreshTokenWithRefresh().pipe(
      switchMap((response: any) => {
        this.authService.saveJWTToken(response.access)
        return next.handle(this.addAuthHeader(req, response.access))
      }),
      catchError((error) => {
        this.authService.doLogout()
        return throwError(error)
      })
    )
  }
}


问:
Tailwind: using suffix instead of prefix for breakpoints
Is there a way to customize breakpoints and use suffixes instead of the usual prefix in tailwind CSS?

Currently, we have this: md:p-4

But I need this: p-4-md

We have a large code base and we are migrating to tailwind CSS and changing all of the previous class names (like p-4-md) to the tailwind prefix (like md:p-4) would be a huge amount of pain.


问:
calling a dictionary value as a function argument?
I am creating a web scraping function. The cities are stored in each link as a number, which I have stored in a dictionary. I want to call the city name as an argument and return the number value, so that the link can be filled with the appropriate number when I run the function. How can I do this?</p>
```<code>def get_data(page_index, city):
        towns_dict = {"charleston": 8, "mount pleasant": 49, "john's island": 40, "folly beach": 22,"daniel island": 188, "james island": 37}

        listings = []
        for i in range(1, 22):
                url = f'https://www.marshallwalker.com/listings/index/page:{page_index}/class:1/status:1,3,6/city:{city}/br:0/br_e:0/fba:0/fba_e:0/hba:0/hba_e:0#real-estate-listings'
                page = requests.get(url=url)

                soup = BeautifulSoup(page.content, 'html.parser')
                properties = soup.find_all('div', class_='summary-right')
                for prop in properties:
                        address = prop.select('div.summary-right h3>a')[0].text
                        price = prop.find('div', class_='s-price').text.replace("\t", "")
                        location = prop.select('small.text-muted')[0].text
                        details = prop.find_all("div", class_='s-cut s-common')
                        details = details[1].text.strip()
                        beds = details[:4]
                        baths = details[6:-11]
                        sqft = details[-9:]

                        listings.append([address, location, price, beds, baths, sqft])
                print(listings)
                print()

get_data("i", "charleston")
</code>```

Body:
I am creating a web scraping function. The cities are stored in each link as a number, which I have stored in a dictionary. I want to call the city name as an argument and return the number value, so that the link can be filled with the appropriate number when I run the function. How can I do this?

def get_data(page_index, city):
        towns_dict = {"charleston": 8, "mount pleasant": 49, "john's island": 40, "folly beach": 22,"daniel island": 188, "james island": 37}

        listings = []
        for i in range(1, 22):
                url = f'https://www.marshallwalker.com/listings/index/page:{page_index}/class:1/status:1,3,6/city:{city}/br:0/br_e:0/fba:0/fba_e:0/hba:0/hba_e:0#real-estate-listings'
                page = requests.get(url=url)

                soup = BeautifulSoup(page.content, 'html.parser')
                properties = soup.find_all('div', class_='summary-right')
                for prop in properties:
                        address = prop.select('div.summary-right h3>a')[0].text
                        price = prop.find('div', class_='s-price').text.replace("\t", "")
                        location = prop.select('small.text-muted')[0].text
                        details = prop.find_all("div", class_='s-cut s-common')
                        details = details[1].text.strip()
                        beds = details[:4]
                        baths = details[6:-11]
                        sqft = details[-9:]

                        listings.append([address, location, price, beds, baths, sqft])
                print(listings)
                print()

get_data("i", "charleston")


问:
Mysql - I'm trying to resolve mysql query. I think it can be done via sbquery
Have a tbl simiar to the following

```<code> col1 col2 col3 col4
  a    b    a
  a    b1   a2   x
  a    b13  a21   x
  b    1b    1a
  b    1b1  a21  v
  b    1b11  a21  v1
</code>```

...

I'm trying to figure out how to do a query that triggers off of col3 'limit 1' for each group of col1

doing

```<code>select * from tblX where col3='a21' limit 1
</code>```

obviously doesn't work

however,

```<code> select * from tblX where col3='a21' and col1='a' limit 1
</code>```

and

```<code> select * from tblX where col3='a21' and col1='b' limit 1
</code>```

would ... but this being multiple operations..

Any pointers on creating a single query?

thanks
obviously doesn't

Body:
Have a tbl simiar to the following

 col1 col2 col3 col4
  a    b    a
  a    b1   a2   x
  a    b13  a21   x
  b    1b    1a
  b    1b1  a21  v
  b    1b11  a21  v1

...

I'm trying to figure out how to do a query that triggers off of col3 'limit 1' for each group of col1

doing

select * from tblX where col3='a21' limit 1

obviously doesn't work

however,

 select * from tblX where col3='a21' and col1='a' limit 1

and

 select * from tblX where col3='a21' and col1='b' limit 1

would ... but this being multiple operations..

Any pointers on creating a single query?

thanks
obviously doesn't


问:
How to get execution date/logical date in PostgresOperator in Airflow?
How do I get access to the execution date in the PostgresOperator in Apache Airflow?

With PythonOperator I get it as below

```<code>def fun(context):
    print(context["execution_date"])
    print(context["logical_date"]) # also the same

task = PythonOperator(
    task_id="python_test",
    python_callable=fun,
)
</code>```

My question is how do I get the same functionality with PostgresOperator.
I have the below task.

```<code>task = PostgresOperator(
    task_id="task_id",
    postgres_conn_id="local_conn",
    sql="sql/some_query.sql"
)
</code>```

and some_query.sql looks like this.

```<code>SELECT *
FROM TABLE
WHERE date = '2022-11-10'
</code>```

I want to parameterize the date above with the execution date.
Something like:

```<code>WHERE date = {{context.logical_date}}
</code>```

How can I achieve that?
also is this the best practice to adjust the behaviour of a task based on a date?

Body:
How do I get access to the execution date in the PostgresOperator in Apache Airflow?

With PythonOperator I get it as below

def fun(context):
    print(context["execution_date"])
    print(context["logical_date"]) # also the same

task = PythonOperator(
    task_id="python_test",
    python_callable=fun,
)

My question is how do I get the same functionality with PostgresOperator.
I have the below task.

task = PostgresOperator(
    task_id="task_id",
    postgres_conn_id="local_conn",
    sql="sql/some_query.sql"
)

and some_query.sql looks like this.

SELECT *
FROM TABLE
WHERE date = '2022-11-10'

I want to parameterize the date above with the execution date.
Something like:

WHERE date = {{context.logical_date}}

How can I achieve that?
also is this the best practice to adjust the behaviour of a task based on a date?


问:
google calendar API list() function stop returning events
was using this to retrieve even from my google calendar:

```<code>all_events = service.events().list(calendarId=calendar_id, timeMax=timeMax, timeMin=timeMin).execute()
</code>```

it was working well, returning correct events from correct calendar but since last week, it stopped working with no edit to the command itself. It still return the correct basic information of the targeted calendar but 'items' is empty list where used to contain all the event informations.

```<code>{'kind': 'calendar#events', 'etag': '"p334b70drr****"', 'summary': 'my calendar', 'description': 'Block time off to dedicate to Finishing. ', 'updated': '2022-12-20T17:16:06.637Z', 'timeZone': 'America/Los_Angeles', 'accessRole': 'owner', 'defaultReminders': [], 'nextSyncToken': 'CMizgbvZi**************', 'items': []}
</code>```

Things I have tried after searching online:

adding parameter: maxResults=9999

adding parameter: nextSync = 'nextSyncToken_returned_in_above_message'

Both not working for me and I have tried these with my other calendars, still same result: returning calendar basic information but not the events.

Could someone please help?

Body:
was using this to retrieve even from my google calendar:

all_events = service.events().list(calendarId=calendar_id, timeMax=timeMax, timeMin=timeMin).execute()

it was working well, returning correct events from correct calendar but since last week, it stopped working with no edit to the command itself. It still return the correct basic information of the targeted calendar but 'items' is empty list where used to contain all the event informations.

{'kind': 'calendar#events', 'etag': '"p334b70drr****"', 'summary': 'my calendar', 'description': 'Block time off to dedicate to Finishing. ', 'updated': '2022-12-20T17:16:06.637Z', 'timeZone': 'America/Los_Angeles', 'accessRole': 'owner', 'defaultReminders': [], 'nextSyncToken': 'CMizgbvZi**************', 'items': []}

Things I have tried after searching online:

adding parameter: maxResults=9999

adding parameter: nextSync = 'nextSyncToken_returned_in_above_message'

Both not working for me and I have tried these with my other calendars, still same result: returning calendar basic information but not the events.

Could someone please help?


问:
How to generate 2D random dataset for PCA
I'm getting started on my ML journey. I'm using the data science handbook to learn about PCA. The following code snippet is used to generate a random 2D data set with a linear relationship. Could someone explain the intuition of how multiplying a 2x2 and 2x200 random matrices results in a linear relationship as shown in the plot?


问:
make increment text with pandas dataframe
I want to make if function with increment text

I already have a function that can append a new line of text to a .txt file with if condition. But it don't know how to make the number of the text increase from 1 to n.
I'm not good at code. Can someone explain to me how to create a function in python?

The condition is like this :

If the value in column dataframe ['similarity'] is greater than 0.5 , and the value in other column dataframe ['polarity'] is "POSITIF". Then , i want to append a new line of text to a .txt file.
ex : given a table like this

text
similarity
polarity

ABCDD
0.6
POSITIF

ASDAS
0.4
NEGATIF

ASGAS
1.0
POSITIF

Here's the code that i use :

```<code>with open("test.txt","a") as myfile:
for key, row in df.iterrows():
    if (row['Similarity'] > 0.5) and ('POSITIF' in row['polarity']):
        myfile.writelines(':membangun(i) rdf:type owl:ObjectProperty ;\n
        rdfs:subPropertyOf :membangun .')
</code>```

The text should be like this :

Body:
I want to make if function with increment text

I already have a function that can append a new line of text to a .txt file with if condition. But it don't know how to make the number of the text increase from 1 to n.
I'm not good at code. Can someone explain to me how to create a function in python?

The condition is like this :

If the value in column dataframe ['similarity'] is greater than 0.5 , and the value in other column dataframe ['polarity'] is "POSITIF". Then , i want to append a new line of text to a .txt file.
ex : given a table like this

text
similarity
polarity

ABCDD
0.6
POSITIF

ASDAS
0.4
NEGATIF

ASGAS
1.0
POSITIF

Here's the code that i use :

with open("test.txt","a") as myfile:
for key, row in df.iterrows():
    if (row['Similarity'] > 0.5) and ('POSITIF' in row['polarity']):
        myfile.writelines(':membangun(i) rdf:type owl:ObjectProperty ;\n
        rdfs:subPropertyOf :membangun .')

The text should be like this :


问:
How to split a large list into multiple smaller lists?
I have an list of 688184 household incomes in df3 also indexed by state, year and serial number and I wanted to have more readable code than the code below. I brute-force manually broke down the lists by state and year as shown below and I was just looking for a more elegant solution using lists or list comprehensions to divide these into smaller lists based on year and state.</p>
```<code>`#Splitting the data by year. Repeated this for 1981, 1982 and 1983.
dfinc1980 = df3[df3["YEAR"] == 1980]

#Further subdividing it by state(The STATEFIP is in integers because we are using state codes.
dfinc1980Alabama = dfinc1980[dfinc1980["STATEFIP"] == 1]
dfinc1980Alaska = dfinc1980[dfinc1980["STATEFIP"] == 2]
dfinc1980Arizona = dfinc1980[dfinc1980["STATEFIP"] == 4]
dfinc1980Arkansas = dfinc1980[dfinc1980["STATEFIP"] == 5]
dfinc1980California = dfinc1980[dfinc1980["STATEFIP"] == 6]
dfinc1980Colorado = dfinc1980[dfinc1980["STATEFIP"] == 8]
dfinc1980Connecticut = dfinc1980[dfinc1980["STATEFIP"] == 9]
dfinc1980Delaware = dfinc1980[dfinc1980["STATEFIP"] == 10]
dfinc1980DC = dfinc1980[dfinc1980["STATEFIP"] == 11]
dfinc1980Florida = dfinc1980[dfinc1980["STATEFIP"] == 12]
dfinc1980Georgia = dfinc1980[dfinc1980["STATEFIP"] == 13]
dfinc1980Hawaii = dfinc1980[dfinc1980["STATEFIP"] == 15]
dfinc1980Idaho = dfinc1980[dfinc1980["STATEFIP"] == 16]
dfinc1980Illinois = dfinc1980[dfinc1980["STATEFIP"] == 17]
dfinc1980Indiana = dfinc1980[dfinc1980["STATEFIP"] == 18]
dfinc1980Iowa = dfinc1980[dfinc1980["STATEFIP"] == 19]
dfinc1980Kansas = dfinc1980[dfinc1980["STATEFIP"] == 20]
dfinc1980Kentucky = dfinc1980[dfinc1980["STATEFIP"] == 21]
dfinc1980Louisiana = dfinc1980[dfinc1980["STATEFIP"] == 22]
dfinc1980Maine = dfinc1980[dfinc1980["STATEFIP"] == 23]
dfinc1980Maryland = dfinc1980[dfinc1980["STATEFIP"] == 24]
dfinc1980Massachusetts = dfinc1980[dfinc1980["STATEFIP"] == 25]
dfinc1980Michigan = dfinc1980[dfinc1980["STATEFIP"] == 26]
dfinc1980Minnesota = dfinc1980[dfinc1980["STATEFIP"] == 27]
dfinc1980Mississippi = dfinc1980[dfinc1980["STATEFIP"] == 28]
dfinc1980Missouri = dfinc1980[dfinc1980["STATEFIP"] == 29]
dfinc1980Montana = dfinc1980[dfinc1980["STATEFIP"] == 30]
dfinc1980Nebraska = dfinc1980[dfinc1980["STATEFIP"] == 31]
dfinc1980Nevada = dfinc1980[dfinc1980["STATEFIP"] == 32]
dfinc1980NewHampshire = dfinc1980[dfinc1980["STATEFIP"] == 33]
dfinc1980NewJersey = dfinc1980[dfinc1980["STATEFIP"] == 34]
dfinc1980NewMexico = dfinc1980[dfinc1980["STATEFIP"] == 35]
dfinc1980NewYork = dfinc1980[dfinc1980["STATEFIP"] == 36]
dfinc1980NorthCarolina = dfinc1980[dfinc1980["STATEFIP"] == 37]
dfinc1980NorthDakota = dfinc1980[dfinc1980["STATEFIP"] == 38]
dfinc1980Ohio = dfinc1980[dfinc1980["STATEFIP"] == 39]
dfinc1980Oklahoma = dfinc1980[dfinc1980["STATEFIP"] == 40]
dfinc1980Oregon = dfinc1980[dfinc1980["STATEFIP"] == 41]
dfinc1980Pennsylvania = dfinc1980[dfinc1980["STATEFIP"] == 42]
dfinc1980RhodeIsland = dfinc1980[dfinc1980["STATEFIP"] == 44]
dfinc1980SouthCarolina = dfinc1980[dfinc1980["STATEFIP"] == 45]
dfinc1980SouthDakota = dfinc1980[dfinc1980["STATEFIP"] == 46]
dfinc1980Tennessee = dfinc1980[dfinc1980["STATEFIP"] == 47]
dfinc1980Texas = dfinc1980[dfinc1980["STATEFIP"] == 48]
dfinc1980Utah = dfinc1980[dfinc1980["STATEFIP"] == 49]
dfinc1980Vermont = dfinc1980[dfinc1980["STATEFIP"] == 50]
dfinc1980Virginia = dfinc1980[dfinc1980["STATEFIP"] == 51]
dfinc1980Washington = dfinc1980[dfinc1980["STATEFIP"] == 53]
dfinc1980WestVirginia = dfinc1980[dfinc1980["STATEFIP"] == 54]
dfinc1980Wisconsin = dfinc1980[dfinc1980["STATEFIP"] == 55]
dfinc1980Wyoming = dfinc1980[dfinc1980["STATEFIP"] == 56]`
</code>```

Body:
I have an list of 688184 household incomes in df3 also indexed by state, year and serial number and I wanted to have more readable code than the code below. I brute-force manually broke down the lists by state and year as shown below and I was just looking for a more elegant solution using lists or list comprehensions to divide these into smaller lists based on year and state.

`#Splitting the data by year. Repeated this for 1981, 1982 and 1983.
dfinc1980 = df3[df3["YEAR"] == 1980]

#Further subdividing it by state(The STATEFIP is in integers because we are using state codes.
dfinc1980Alabama = dfinc1980[dfinc1980["STATEFIP"] == 1]
dfinc1980Alaska = dfinc1980[dfinc1980["STATEFIP"] == 2]
dfinc1980Arizona = dfinc1980[dfinc1980["STATEFIP"] == 4]
dfinc1980Arkansas = dfinc1980[dfinc1980["STATEFIP"] == 5]
dfinc1980California = dfinc1980[dfinc1980["STATEFIP"] == 6]
dfinc1980Colorado = dfinc1980[dfinc1980["STATEFIP"] == 8]
dfinc1980Connecticut = dfinc1980[dfinc1980["STATEFIP"] == 9]
dfinc1980Delaware = dfinc1980[dfinc1980["STATEFIP"] == 10]
dfinc1980DC = dfinc1980[dfinc1980["STATEFIP"] == 11]
dfinc1980Florida = dfinc1980[dfinc1980["STATEFIP"] == 12]
dfinc1980Georgia = dfinc1980[dfinc1980["STATEFIP"] == 13]
dfinc1980Hawaii = dfinc1980[dfinc1980["STATEFIP"] == 15]
dfinc1980Idaho = dfinc1980[dfinc1980["STATEFIP"] == 16]
dfinc1980Illinois = dfinc1980[dfinc1980["STATEFIP"] == 17]
dfinc1980Indiana = dfinc1980[dfinc1980["STATEFIP"] == 18]
dfinc1980Iowa = dfinc1980[dfinc1980["STATEFIP"] == 19]
dfinc1980Kansas = dfinc1980[dfinc1980["STATEFIP"] == 20]
dfinc1980Kentucky = dfinc1980[dfinc1980["STATEFIP"] == 21]
dfinc1980Louisiana = dfinc1980[dfinc1980["STATEFIP"] == 22]
dfinc1980Maine = dfinc1980[dfinc1980["STATEFIP"] == 23]
dfinc1980Maryland = dfinc1980[dfinc1980["STATEFIP"] == 24]
dfinc1980Massachusetts = dfinc1980[dfinc1980["STATEFIP"] == 25]
dfinc1980Michigan = dfinc1980[dfinc1980["STATEFIP"] == 26]
dfinc1980Minnesota = dfinc1980[dfinc1980["STATEFIP"] == 27]
dfinc1980Mississippi = dfinc1980[dfinc1980["STATEFIP"] == 28]
dfinc1980Missouri = dfinc1980[dfinc1980["STATEFIP"] == 29]
dfinc1980Montana = dfinc1980[dfinc1980["STATEFIP"] == 30]
dfinc1980Nebraska = dfinc1980[dfinc1980["STATEFIP"] == 31]
dfinc1980Nevada = dfinc1980[dfinc1980["STATEFIP"] == 32]
dfinc1980NewHampshire = dfinc1980[dfinc1980["STATEFIP"] == 33]
dfinc1980NewJersey = dfinc1980[dfinc1980["STATEFIP"] == 34]
dfinc1980NewMexico = dfinc1980[dfinc1980["STATEFIP"] == 35]
dfinc1980NewYork = dfinc1980[dfinc1980["STATEFIP"] == 36]
dfinc1980NorthCarolina = dfinc1980[dfinc1980["STATEFIP"] == 37]
dfinc1980NorthDakota = dfinc1980[dfinc1980["STATEFIP"] == 38]
dfinc1980Ohio = dfinc1980[dfinc1980["STATEFIP"] == 39]
dfinc1980Oklahoma = dfinc1980[dfinc1980["STATEFIP"] == 40]
dfinc1980Oregon = dfinc1980[dfinc1980["STATEFIP"] == 41]
dfinc1980Pennsylvania = dfinc1980[dfinc1980["STATEFIP"] == 42]
dfinc1980RhodeIsland = dfinc1980[dfinc1980["STATEFIP"] == 44]
dfinc1980SouthCarolina = dfinc1980[dfinc1980["STATEFIP"] == 45]
dfinc1980SouthDakota = dfinc1980[dfinc1980["STATEFIP"] == 46]
dfinc1980Tennessee = dfinc1980[dfinc1980["STATEFIP"] == 47]
dfinc1980Texas = dfinc1980[dfinc1980["STATEFIP"] == 48]
dfinc1980Utah = dfinc1980[dfinc1980["STATEFIP"] == 49]
dfinc1980Vermont = dfinc1980[dfinc1980["STATEFIP"] == 50]
dfinc1980Virginia = dfinc1980[dfinc1980["STATEFIP"] == 51]
dfinc1980Washington = dfinc1980[dfinc1980["STATEFIP"] == 53]
dfinc1980WestVirginia = dfinc1980[dfinc1980["STATEFIP"] == 54]
dfinc1980Wisconsin = dfinc1980[dfinc1980["STATEFIP"] == 55]
dfinc1980Wyoming = dfinc1980[dfinc1980["STATEFIP"] == 56]`


问:
Mod_wsgi server will not start up
I am moving a currently working Django project to a new Red Hat server and upon moving the project, it's virtual env, and installing pip packages I started up the server how I always have and it worked fine. Going back to it a week later I enter in the web address of the django site and it times out. The mod_wsgi error log reads.

```<code>[Tue Dec 20 17:55:49.282343 2022] [core:warn] [pid 831143:tid 139775964862784] AH00098: pid file /tmp/mod_wsgi-localhost:8080:21056/httpd.pid overwritten -- Unclean shutdown of previous Apache run?
[Tue Dec 20 17:55:49.283800 2022] [mpm_event:notice] [pid 831143:tid 139775964862784] AH00489: Apache/2.4.37 (Red Hat Enterprise Linux) mod_wsgi/4.9.4 Python/3.6 configured -- resuming normal operations
[Tue Dec 20 17:55:49.283823 2022] [core:notice] [pid 831143:tid 139775964862784] AH00094: Command line: 'httpd (mod_wsgi-express)    -f /tmp/mod_wsgi-localhost:8080:21056/httpd.conf -D MOD_WSGI_KEEP_ALIVE -D MOD_WSGI_MPM_ENABLE_EVENT_MODULE -D MOD_WSGI_MPM_EXISTS_EVENT_MODULE -D MOD_WSGI_MPM_EXISTS_WORKER_MODULE -D MOD_WSGI_MPM_EXISTS_PREFORK_MODULE -D FOREGROUND'
</code>```

I can't figure out what this error indicates is happening.

```<code>httpd.pid overwritten -- Unclean shutdown of previous Apache run?
</code>```

I've even restarted the apache server that runs on this server and it has done nothing.

Title: Mod_wsgi server will not start up

Body:
I am moving a currently working Django project to a new Red Hat server and upon moving the project, it's virtual env, and installing pip packages I started up the server how I always have and it worked fine. Going back to it a week later I enter in the web address of the django site and it times out. The mod_wsgi error log reads.

[Tue Dec 20 17:55:49.282343 2022] [core:warn] [pid 831143:tid 139775964862784] AH00098: pid file /tmp/mod_wsgi-localhost:8080:21056/httpd.pid overwritten -- Unclean shutdown of previous Apache run?
[Tue Dec 20 17:55:49.283800 2022] [mpm_event:notice] [pid 831143:tid 139775964862784] AH00489: Apache/2.4.37 (Red Hat Enterprise Linux) mod_wsgi/4.9.4 Python/3.6 configured -- resuming normal operations
[Tue Dec 20 17:55:49.283823 2022] [core:notice] [pid 831143:tid 139775964862784] AH00094: Command line: 'httpd (mod_wsgi-express)    -f /tmp/mod_wsgi-localhost:8080:21056/httpd.conf -D MOD_WSGI_KEEP_ALIVE -D MOD_WSGI_MPM_ENABLE_EVENT_MODULE -D MOD_WSGI_MPM_EXISTS_EVENT_MODULE -D MOD_WSGI_MPM_EXISTS_WORKER_MODULE -D MOD_WSGI_MPM_EXISTS_PREFORK_MODULE -D FOREGROUND'

I can't figure out what this error indicates is happening.

httpd.pid overwritten -- Unclean shutdown of previous Apache run?

I've even restarted the apache server that runs on this server and it has done nothing.


问:
Supabase SessionContextProvider causes unnecessary re-renders
Following Supabase's Next.js Quickstart, after logging in the index page re-renders everytime I:

Switch from another browser tab back to my application's tab

Switch to full screen mode

Switch from full screen mode back to window mode.

Tested on Mac OS Safari and Chrome. According to the profiler tool, it is SessionContextProvider that causes the updates. It also causes the view to flash a lodading state, because Account page fetches user data on every render.

First I would like to get rid of this behavior where the view re-renders when the user is switching between tabs and full screen modes.

Second, I want to consider if the session should be fetched server-side, although this might be a topic for another post.

The example project is found here.