问:
How do I download a generated csv in magento 2.4.5
My files so far are:

system.xml

```<code><field id="generate_csv" translate="label" type="button" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="1">
   <label>Generate Categories CSV</label>
  <frontend_model>Vendor\Module\Block\Adminhtml\System\Config\Button</frontend_model>
</field>
</code>```

button.php

```<code><?php
namespace [Vendor]\[Module]\Block\Adminhtml\System\Config;
use Magento\Config\Block\System\Config\Form\Field;
use Magento\Backend\Block\Template\Context;
use Magento\Framework\Data\Form\Element\AbstractElement;

class Button extends Field
{
    protected $_template = 'Vendor_Module::system/config/button.phtml';

    public function __construct(
        Context $context,
        array $data = []
    ){
        parent::__construct($context, $data);
    }

    public function render(AbstractElement $element)
    {
        $element->unsScope()->unsCanUseWebsiteValue()->unsCanUseDefaultValue();
        return parent::render($element);
    }

    protected function _getElementHtml(AbstractElement $element)
    {
        return $this->_toHtml();
    }

    public function getAjaxUrl()
    {
        return $this->getUrl('[router]/Export/CategoryExport');
    }

    public function getButtonHtml()
    {
        $button = $this->getLayout()->createBlock(
            'Magento\Backend\Block\Widget\Button'
        )->setData(
            [
                'id' => 'generate_csv',
                'label' => __('Generate CSV')
            ]
        );
        return $button->toHtml();
    }
}
</code>```

button.phtml

```<code><script>
    require([
        'jquery',
        'prototype'
    ], function ($) {

        $('#generate_csv').click(function () {
            var params = {};
            new Ajax.Request('<?php echo $block->getAjaxUrl() ?>', {
                parameters: params,
                loaderArea: false,
                asynchronous: true,
                onCreate: function () {
                    $('#custom_button_response_message').text('');
                },
                onSuccess: function (transport) {
                    var resultText = '';
                    if (transport.status > 200) {
                        resultText = transport.statusText;
                    } else {
                        var response = JSON.parse(transport.responseText);
                        resultText = response.message
                    }
                    $('#generate_csv_response_message').text(resultText);

                }
            });
        });
    });
</script>
<?php echo $block->getButtonHtml(); ?>
<p>
    <span id="generate_csv_response_message"></span>
</p>
</code>```

controller

```<code><?php
namespace [Vendor]\[Module]\Controller\Adminhtml\Export;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\Json;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Filesystem;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory;
use Magento\Catalog\Model\CategoryFactory;

class CategoryExport extends Action
{
    protected $resultJsonFactory;

    /**
     * @param Context $context
     * @param JsonFactory $resultJsonFactory
     */
    public function __construct(
        Context $context,
        JsonFactory $resultJsonFactory,
        Filesystem $filesystem,
        DirectoryList $directoryList,
        CollectionFactory $categoryCollectionFactory,
        CategoryFactory $categoryFactory
    ){
        $this->resultJsonFactory = $resultJsonFactory;
        $this->filesystem = $filesystem;
        $this->directory = $filesystem->getDirectoryWrite(DirectoryList::VAR_DIR);
        $this->categoryCollectionFactory = $categoryCollectionFactory;
        $this->categoryFactory = $categoryFactory;
        parent::__construct($context);
    }

    /**
     * @return Json
     */
    public function execute()
    {
        $message = 'Success';
        $data[] = [
            'id' => __('Entity ID'),
            'name' => __('Name'),
            'level' => __('Level')
        ];

        $categoryCollection = $this->categoryCollectionFactory->create();
        $categoryCollection->addAttributeToSelect('*');
        $filepath = 'export/customerlist.csv';
        $this->directory->create('export');
        $stream = $this->directory->openFile($filepath, 'w+');
        $stream->lock();
        $header = ['Id', 'Name', 'Level'];
        $stream->writeCsv($header);

        //$categoryArray = array();
        foreach ($categoryCollection as $category) {
            $data = [];
            $data[] = $category->getId();
            $data[] = $category->getName();
            $data[] = $category->getLevel();
            $stream->writeCsv($data);
        }

        /** @var Json $result */
        $result = $this->resultJsonFactory->create();

        return $result->setData(['message' => $message]);
    }

}
</code>```

This creates a csv file in var/export directory but I cannot download it
Can anyone help explain how to modify the code so that it will automatically create and down the csv.

I have tried following various examples on the web but none of them have worked.

Please help me out

Body:
My files so far are:

system.xml

<field id="generate_csv" translate="label" type="button" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="1">
   Generate Categories CSV
  <frontend_model>Vendor\Module\Block\Adminhtml\System\Config\Button</frontend_model>
</field>

button.php

<?php
namespace [Vendor]\[Module]\Block\Adminhtml\System\Config;
use Magento\Config\Block\System\Config\Form\Field;
use Magento\Backend\Block\Template\Context;
use Magento\Framework\Data\Form\Element\AbstractElement;

class Button extends Field
{
    protected $_template = 'Vendor_Module::system/config/button.phtml';

    public function __construct(
        Context $context,
        array $data = []
    ){
        parent::__construct($context, $data);
    }

    public function render(AbstractElement $element)
    {
        $element->unsScope()->unsCanUseWebsiteValue()->unsCanUseDefaultValue();
        return parent::render($element);
    }

    protected function _getElementHtml(AbstractElement $element)
    {
        return $this->_toHtml();
    }

    public function getAjaxUrl()
    {
        return $this->getUrl('[router]/Export/CategoryExport');
    }

    public function getButtonHtml()
    {
        $button = $this->getLayout()->createBlock(
            'Magento\Backend\Block\Widget\Button'
        )->setData(
            [
                'id' => 'generate_csv',
                'label' => __('Generate CSV')
            ]
        );
        return $button->toHtml();
    }
}

button.phtml

<?php echo $block->getButtonHtml(); ?>

controller

<?php
namespace [Vendor]\[Module]\Controller\Adminhtml\Export;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\Json;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Filesystem;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory;
use Magento\Catalog\Model\CategoryFactory;

class CategoryExport extends Action
{
    protected $resultJsonFactory;

    /**
     * @param Context $context
     * @param JsonFactory $resultJsonFactory
     */
    public function __construct(
        Context $context,
        JsonFactory $resultJsonFactory,
        Filesystem $filesystem,
        DirectoryList $directoryList,
        CollectionFactory $categoryCollectionFactory,
        CategoryFactory $categoryFactory
    ){
        $this->resultJsonFactory = $resultJsonFactory;
        $this->filesystem = $filesystem;
        $this->directory = $filesystem->getDirectoryWrite(DirectoryList::VAR_DIR);
        $this->categoryCollectionFactory = $categoryCollectionFactory;
        $this->categoryFactory = $categoryFactory;
        parent::__construct($context);
    }

    /**
     * @return Json
     */
    public function execute()
    {
        $message = 'Success';
        $data[] = [
            'id' => __('Entity ID'),
            'name' => __('Name'),
            'level' => __('Level')
        ];

        $categoryCollection = $this->categoryCollectionFactory->create();
        $categoryCollection->addAttributeToSelect('*');
        $filepath = 'export/customerlist.csv';
        $this->directory->create('export');
        $stream = $this->directory->openFile($filepath, 'w+');
        $stream->lock();
        $header = ['Id', 'Name', 'Level'];
        $stream->writeCsv($header);

        //$categoryArray = array();
        foreach ($categoryCollection as $category) {
            $data = [];
            $data[] = $category->getId();
            $data[] = $category->getName();
            $data[] = $category->getLevel();
            $stream->writeCsv($data);
        }

        /** @var Json $result */
        $result = $this->resultJsonFactory->create();

        return $result->setData(['message' => $message]);
    }

}

This creates a csv file in var/export directory but I cannot download it
Can anyone help explain how to modify the code so that it will automatically create and down the csv.

I have tried following various examples on the web but none of them have worked.

Please help me out


来源: stackexchange

问:
Python-VLC Errors When Opening Video File and Skipping Video Playback Position
I'm working on a project making a semi-randomized video player on the Raspberry Pi 4 (64-bit OS with Desktop) using Python-VLC. I have a proof of concept working, but I get some strange error messages whenever I open a new video file or skip the playback position.

Here is the error when a new file is opened:

```<code>[0000007f680013e0] mmal_xsplitter vout display error: Failed to open Xsplitter:opengles2 module
[0000007f680013e0] mmal_xsplitter vout display error: Failed to open Xsplitter:mmal_vout module
[0000007f6c013b10] avcodec decoder: Using DRM Video Accel for hardware decoding
</code>```

Here is the error when I skip playback position:

```<code>[0000007f6c013b10] main decoder error: Timestamp conversion failed for 315848867: no reference clock
[0000007f6c013b10] main decoder error: Could not convert timestamp 0 for FFmpeg
</code>```

The program seems to work in spite of these, but there's some minor lag I'd like to get rid of, and I want to make sure a problem doesn't arise from these errors piling up since I plan on running this program continuously for long periods of time.

Can anyone help explain what these errors mean and how I can get rid of them?

Here is the code I am using:

```<code>import vlc
import RPi.GPIO as GPIO
import time
import pygame
import random

def mute():
    media_player.get_media_player().audio_set_volume(0)

opin = 2
ipin = 4

pos = [0, 0]
index = 0

GPIO.setmode(GPIO.BCM)
GPIO.setup(opin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(ipin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

player = vlc.Instance("--no-xlib")

media_player = player.media_list_player_new()

media_list = player.media_list_new()

media = player.media_new("/home/hhaudio/Desktop/Malice.mp4")
media_list.add_media(media)

media = player.media_new("/home/hhaudio/Desktop/Croc.mp4")
media_list.add_media(media)

media_player.set_media_list(media_list)
media_player.play_item_at_index(0)

mute()

print("hello!")

nextvid = 1

while True:

    if GPIO.input(opin) == 0:
        print("exit")
        exit()
        break
    if GPIO.input(ipin) == 0 and nextvid == 1:
        print("ipin")
        media_player.get_media_player().set_position(random.random())
    nextvid = GPIO.input(ipin)
    time.sleep(0.001)
</code>```

As a bonus, are there any recommendations y'all can give about how I could optimize things to make playback faster with VLC settings, etc?

Ran my program, according to my understanding of the VLC documentation. Works but is slightly laggy and throws errors.

ContentLicense: CC BY-SA 4.0

Body:
I'm working on a project making a semi-randomized video player on the Raspberry Pi 4 (64-bit OS with Desktop) using Python-VLC. I have a proof of concept working, but I get some strange error messages whenever I open a new video file or skip the playback position.

Here is the error when a new file is opened:

[0000007f680013e0] mmal_xsplitter vout display error: Failed to open Xsplitter:opengles2 module
[0000007f680013e0] mmal_xsplitter vout display error: Failed to open Xsplitter:mmal_vout module
[0000007f6c013b10] avcodec decoder: Using DRM Video Accel for hardware decoding

Here is the error when I skip playback position:

[0000007f6c013b10] main decoder error: Timestamp conversion failed for 315848867: no reference clock
[0000007f6c013b10] main decoder error: Could not convert timestamp 0 for FFmpeg

The program seems to work in spite of these, but there's some minor lag I'd like to get rid of, and I want to make sure a problem doesn't arise from these errors piling up since I plan on running this program continuously for long periods of time.

Can anyone help explain what these errors mean and how I can get rid of them?

Here is the code I am using:

import vlc
import RPi.GPIO as GPIO
import time
import pygame
import random

def mute():
    media_player.get_media_player().audio_set_volume(0)

opin = 2
ipin = 4

pos = [0, 0]
index = 0

GPIO.setmode(GPIO.BCM)
GPIO.setup(opin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(ipin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

player = vlc.Instance("--no-xlib")

media_player = player.media_list_player_new()

media_list = player.media_list_new()

media = player.media_new("/home/hhaudio/Desktop/Malice.mp4")
media_list.add_media(media)

media = player.media_new("/home/hhaudio/Desktop/Croc.mp4")
media_list.add_media(media)

media_player.set_media_list(media_list)
media_player.play_item_at_index(0)

mute()

print("hello!")

nextvid = 1

while True:

    if GPIO.input(opin) == 0:
        print("exit")
        exit()
        break
    if GPIO.input(ipin) == 0 and nextvid == 1:
        print("ipin")
        media_player.get_media_player().set_position(random.random())
    nextvid = GPIO.input(ipin)
    time.sleep(0.001)

As a bonus, are there any recommendations y'all can give about how I could optimize things to make playback faster with VLC settings, etc?

Ran my program, according to my understanding of the VLC documentation. Works but is slightly laggy and throws errors.


问:
Connection between my html file and my app.js
So i want to insert in my database the name/password inserted into my html formulary.
i think my fuction is working but idk how to get the date inserted into my login field.
If you can tell me what i have to put after let name and let password it could be usefull. thanks</p>
```<code>app.get('/login', (req, res) => {

let name =
let password =
req.getConnection((erreur, connection)=>{
    if(erreur){
        console.log(erreur);
    }else{
        connection.query('INSERT INTO user(id,name,password)
values(?,?,?)',
         [null,name,password ],
         (erreur, resultat)=>{
            if(erreur){
                console.log(erreur)
            }else{
                res.status(300).redirect("/login")
            }
        })
    }
})
res.render('login')
})

<body>
<div class="Hero">
    <div class="form-box">
        <div class="button-box">
            <div id="btn"></div>
            <button type="button" class="toggle-btn" onclick="login()">Se connecter</button>
            <button type="button" class="toggle-btn" onclick="register()">S'enregistrer</button>
        </div>
        <div class="logo">
            <img src="img/ucl.png">

        </div>
        <form id="login" class="input-group">
            <input type="text" class="input-field" placeholder="Nom d'utilisateur" required>
            <input type="text" class="input-field2" placeholder="Mot de passe" required>
            <input type="checkbox" class="check-box"><span>Se rappeler du mot du mot de passe</span>
            <button type="submit" class="submit-btn">Se connecter</button>
        </form>
        <form id ="register" class="input-group">
            <input type="text" class="input-field" placeholder="Nom d'utilisateur" required>
            <input type="email" class="input-field" placeholder="Email" required>
            <input type="text" class="input-field" placeholder="Mot de passe" required>
            <input type="checkbox" class="check-box"><span>J'accepte les conditions d'utilisations</span>
            <button type="submit" class="submit-btn">s'enregistrer</button>
        </form>
    </div>

</div>
</code>```

Body:
So i want to insert in my database the name/password inserted into my html formulary.
i think my fuction is working but idk how to get the date inserted into my login field.
If you can tell me what i have to put after let name and let password it could be usefull. thanks

app.get('/login', (req, res) => {

let name =
let password =
req.getConnection((erreur, connection)=>{
    if(erreur){
        console.log(erreur);
    }else{
        connection.query('INSERT INTO user(id,name,password)
values(?,?,?)',
         [null,name,password ],
         (erreur, resultat)=>{
            if(erreur){
                console.log(erreur)
            }else{
                res.status(300).redirect("/login")
            }
        })
    }
})
res.render('login')
})

            <button type="button" class="toggle-btn" onclick="login()">Se connecter</button>
            <button type="button" class="toggle-btn" onclick="register()">S'enregistrer</button>

        <form id="login" class="input-group">
            <input type="text" class="input-field" placeholder="Nom d'utilisateur" required>
            <input type="text" class="input-field2" placeholder="Mot de passe" required>
            <input type="checkbox" class="check-box">Se rappeler du mot du mot de passe
            <button type="submit" class="submit-btn">Se connecter</button>
        </form>
        <form id ="register" class="input-group">
            <input type="text" class="input-field" placeholder="Nom d'utilisateur" required>
            <input type="email" class="input-field" placeholder="Email" required>
            <input type="text" class="input-field" placeholder="Mot de passe" required>
            <input type="checkbox" class="check-box">J'accepte les conditions d'utilisations
            <button type="submit" class="submit-btn">s'enregistrer</button>
        </form>


问:
Why ReferenceError: setImmediate is not defined, when I'm not using it at all?
I've created a tiny app with React and Nest, to understand WebScoket api.
Not to just waste time, I wanted to wrap it as a deployable app, and host it somewhere.

The code is here: https://github.com/An1mus/chitchat

While adding some basic workflows, I've faced an issue with the following error, that appears after running the tests (the test cases are passing):

```<code>/Users/andrewpetrov/Projects/an1mus/chitchat/client/node_modules/.pnpm/xmlhttprequest-ssl@2.0.0/node_modules/xmlhttprequest-ssl/lib/XMLHttpRequest.js:628
        setImmediate(function() { self["on" + event]() })
        ^

ReferenceError: setImmediate is not defined
    at XMLHttpRequest.dispatchEvent (/Users/andrewpetrov/Projects/an1mus/chitchat/client/node_modules/.pnpm/xmlhttprequest-ssl@2.0.0/node_modules/xmlhttprequest-ssl/lib/XMLHttpRequest.js:628:9)
    at setState (/Users/andrewpetrov/Projects/an1mus/chitchat/client/node_modules/.pnpm/xmlhttprequest-ssl@2.0.0/node_modules/xmlhttprequest-ssl/lib/XMLHttpRequest.js:654:12)
    at XMLHttpRequest.handleError (/Users/andrewpetrov/Projects/an1mus/chitchat/client/node_modules/.pnpm/xmlhttprequest-ssl@2.0.0/node_modules/xmlhttprequest-ssl/lib/XMLHttpRequest.js:572:5)
    at ClientRequest.errorHandler (/Users/andrewpetrov/Projects/an1mus/chitchat/client/node_modules/.pnpm/xmlhttprequest-ssl@2.0.0/node_modules/xmlhttprequest-ssl/lib/XMLHttpRequest.js:490:14)
    at ClientRequest.emit (node:events:527:28)
    at Socket.socketErrorListener (node:_http_client:454:9)
    at Socket.emit (node:events:527:28)
    at emitErrorNT (node:internal/streams/destroy:164:8)
    at emitErrorCloseNT (node:internal/streams/destroy:129:3)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)

</code>```

For some reason it fires, when I run tests, even though my only test is this:

```<code>import React from 'react';
import { render } from '@testing-library/react';
import App from './App';

test('renders the app', async () => {
  // this is a workaround for issue #1695 in jsdom
  window.HTMLElement.prototype.scrollIntoView = function() {};

  const {container} = await render(<App />);
  expect(container.querySelector('h1')).toHaveTextContent('Welcome to ChitChat')
});
</code>```

The test runs with react-scripts test --watchAll=false

What can cause an error like that?
My guess was that I wrote the test incorrectly, of it is somehow related to WebScokets being rendered along side the App.

I'll be grateful for any hint.

Body:
I've created a tiny app with React and Nest, to understand WebScoket api.
Not to just waste time, I wanted to wrap it as a deployable app, and host it somewhere.

The code is here: https://github.com/An1mus/chitchat

While adding some basic workflows, I've faced an issue with the following error, that appears after running the tests (the test cases are passing):

/Users/andrewpetrov/Projects/an1mus/chitchat/client/node_modules/.pnpm/xmlhttprequest-ssl@2.0.0/node_modules/xmlhttprequest-ssl/lib/XMLHttpRequest.js:628
        setImmediate(function() { self["on" + event]() })
        ^

ReferenceError: setImmediate is not defined
    at XMLHttpRequest.dispatchEvent (/Users/andrewpetrov/Projects/an1mus/chitchat/client/node_modules/.pnpm/xmlhttprequest-ssl@2.0.0/node_modules/xmlhttprequest-ssl/lib/XMLHttpRequest.js:628:9)
    at setState (/Users/andrewpetrov/Projects/an1mus/chitchat/client/node_modules/.pnpm/xmlhttprequest-ssl@2.0.0/node_modules/xmlhttprequest-ssl/lib/XMLHttpRequest.js:654:12)
    at XMLHttpRequest.handleError (/Users/andrewpetrov/Projects/an1mus/chitchat/client/node_modules/.pnpm/xmlhttprequest-ssl@2.0.0/node_modules/xmlhttprequest-ssl/lib/XMLHttpRequest.js:572:5)
    at ClientRequest.errorHandler (/Users/andrewpetrov/Projects/an1mus/chitchat/client/node_modules/.pnpm/xmlhttprequest-ssl@2.0.0/node_modules/xmlhttprequest-ssl/lib/XMLHttpRequest.js:490:14)
    at ClientRequest.emit (node:events:527:28)
    at Socket.socketErrorListener (node:_http_client:454:9)
    at Socket.emit (node:events:527:28)
    at emitErrorNT (node:internal/streams/destroy:164:8)
    at emitErrorCloseNT (node:internal/streams/destroy:129:3)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)

For some reason it fires, when I run tests, even though my only test is this:

import React from 'react';
import { render } from '@testing-library/react';
import App from './App';

test('renders the app', async () => {
  // this is a workaround for issue #1695 in jsdom
  window.HTMLElement.prototype.scrollIntoView = function() {};

  const {container} = await render(<App />);
  expect(container.querySelector('h1')).toHaveTextContent('Welcome to ChitChat')
});

The test runs with react-scripts test --watchAll=false

What can cause an error like that?
My guess was that I wrote the test incorrectly, of it is somehow related to WebScokets being rendered along side the App.

I'll be grateful for any hint.


问:
Create a list of generic interfaces with the classes, that implement the interrace
I have the following classes & interfaces:

public interface IValueMapper<TData>{ }

public class MyMapper : IValueMapper<IMyType> { }

public class MyRecord : BaseType, IMyType

I am trying to create the following list:

```<code>var mappers = new List<IValueMapper<MyRecord>>{new MyMapper() };
</code>```

but I get Compiler Error CS1503.

Is there a way to create the list I want?

Body:
I have the following classes & interfaces:

public interface IValueMapper<TData>{ }

public class MyMapper : IValueMapper<IMyType> { }

public class MyRecord : BaseType, IMyType

I am trying to create the following list:

var mappers = new List<IValueMapper<MyRecord>>{new MyMapper() };

but I get Compiler Error CS1503.

Is there a way to create the list I want?


问:
No LLDB Debugger in Codeline In MacOS Environment

I have a MacOS. On Xcode, I have lldb. However, when there is no LLDB option in Codelite despite using a MAC. Why? How do I get back lldb? Thanks a lot.

I looked into settings--> GDB Settings but only found GNU debugger and pre-defined types which was none. I do not see LLDB which I was expecting.


问:
Hotjar onLoaded event
I'm using Hotjar tool (https://www.hotjar.com/)

I've put their snippet (which loads their code) on my page as instructed

I wonder if there is a onLoaded event, because I need to fire an event setting the state when the Hotjar is finally loaded (setting the state is what one has to do for SPA to tell Hotjar that the screen has changed)

I could create my checker function waiting until window.hj is defined, but I prefer to use the built-in one, if there is

Unfortunately the documentation is not great for developers (probably because they aim the companies without developers)

Title: Hotjar onLoaded event


问:
Is there Custom List that can be clicked in pyqt5
I have an idea to create a list from data from mySQL database but i dont know which widget should i use in the qt.
What i wanna create is when i import data from my database it can be show in my interface and i can choose the value from it.
example :
i have database : id,name,age
1,yudi,13
2,rian,19
then my interface show all name : choose name
----
yudi
rian

-----
save
how to create like that?

right now i just use Qcombo box, but i want to show all choice in list from top to button and i can pick one from that list


问:
How to store in cert store standard.licensing KeyPair?
I need to license my software and in order to do so I use a module called standard.license for both the key generation part and the license signing.

```<code>using standard.licensing;

string _passPhrase = "somePrase";

KeyGenerator keyGenerator = KeyGenerator.Create();
KeyPair keyPair = keyGenerator.GenerateKeyPair();

string privateKey = keyPair.ToEncryptedPrivateKeyString(_passPhrase);
string privateKey = keyPair.ToPublicKeyString();

Standard.Licensing.License license = Standard.Licensing.License.New()
    .WithUniqueIdentifier(Guid.NewGuid())
    .ExpiresAt(expiryDate)
    .WithAdditionalAttributes(licenseAttributes)
    .LicensedTo((c) => c.Name = customerName)
    .CreateAndSignWithPrivateKey(_privateKey, _passPhrase);
</code>```

After I generate the key pair and the license, I stored the license string in the windows registry.
In addition, I would like to create a certificate from my keypair so I could store it in the certificate store. (The client only need a certificate with the public key, as the private key is only used by the software seller).

The problem is that I have no idea how exactly can I create a certificate from those keys.

As far as I know, standard.licensing is derived from protable.licensing, and the later one uses bouncycastle. On top of that, I think the encryption is probably ECDSA prime256v1.

I've used openssl in the past, I am not sure what do I have to do in order to create a certificate from the keys I've perviosly generated.

Can I somehow  create a public.pem or client.crt file from these "string" keys?

Thanks ahead,

P.S. I stricIy prefer not to save the keys as local files.

Portable.Licensing - GitHub
Standard.Licensing - GitHub

Body:
I need to license my software and in order to do so I use a module called standard.license for both the key generation part and the license signing.

using standard.licensing;

string _passPhrase = "somePrase";

KeyGenerator keyGenerator = KeyGenerator.Create();
KeyPair keyPair = keyGenerator.GenerateKeyPair();

string privateKey = keyPair.ToEncryptedPrivateKeyString(_passPhrase);
string privateKey = keyPair.ToPublicKeyString();

Standard.Licensing.License license = Standard.Licensing.License.New()
    .WithUniqueIdentifier(Guid.NewGuid())
    .ExpiresAt(expiryDate)
    .WithAdditionalAttributes(licenseAttributes)
    .LicensedTo((c) => c.Name = customerName)
    .CreateAndSignWithPrivateKey(_privateKey, _passPhrase);

After I generate the key pair and the license, I stored the license string in the windows registry.
In addition, I would like to create a certificate from my keypair so I could store it in the certificate store. (The client only need a certificate with the public key, as the private key is only used by the software seller).

The problem is that I have no idea how exactly can I create a certificate from those keys.

As far as I know, standard.licensing is derived from protable.licensing, and the later one uses bouncycastle. On top of that, I think the encryption is probably ECDSA prime256v1.

I've used openssl in the past, I am not sure what do I have to do in order to create a certificate from the keys I've perviosly generated.

Can I somehow  create a public.pem or client.crt file from these "string" keys?

Thanks ahead,

P.S. I stricIy prefer not to save the keys as local files.

Portable.Licensing - GitHub
Standard.Licensing - GitHub


问:
Calculate change rate of a variable in a given time in Python
I'm working on a project with a Raspberry Pi and a Parallax 360 servo widh feedback and pigpio library. What I'm trying to accomplish is to determine programatically the min and max pulse width I could send to the servo in both rotation directions.

These values are shown in the servo's datasheet, however I would like to code a "calibrate" function since this absolute values might vary a little from unit to unit, as I verified with my classmates'. (BTW, minimum PW is 1280 µS for max speed in one direction whereas maximum PW is 1720 µS for max speed in the opposite direction, where around 1500 µS means 0 RPM)

The feedback signal is also documented on said datasheet, and I am able to read it. It is also a PWM signal which will vary from 2.9% to 97.1% duty cycle depending on the shaft angle. I thought that if I'm able to gather samples of this signal in a given window of time, I would be able to calculate how quickly it's spinning at different control signals.

Assuming that the servo speed is constant at a constant control signal, changes on this "rate" or "slope" for the feedback duty cycle signal, will indicate that the servo is accelerating or decelerating. Cool. This is the procedure I thought to find the limits:

Start below the absolute minimum (1280 µS) where the servo will spin at its maximum speed, and start increasing the duty cycle of the control signal until I can detect a deceleration on the feedback signal, indicating that I found the real minimum control PW.

Continue increasing the duty cycle of the control signal, until the "slope" is zero, which means the servo stopped and I found the next bound.

Continue increasing the duty cycle of the control signal, until I detect and acceleration on the feedback signal which will indicate the servo started to move again (In the opposite direction, OFC)

Continue increasing the duty cycle of the control signal, observing the acceleration "slope" until this slope is zero, which means the servo have reached its maximum speed.

The problem... I don't really have a clue on the maths involved or needed to calculate this. This is my code by now (This is a method part of the class I'm coding meant to control the servo):

Thanks @101 about the issue of variables' name. Before this I was coding the class itself and thus the confusing naming. Do not take that on consideration!

    def calibrate(self):
        __PW_STEP = 10 # Pulse width increasing step
        __MIN_PW = self.__MAX_CW_PW - 100.0 # self.__MAX_CW_PW = 1280 µS
        __MAX_PW = self.__MAX_CCW_PW + 100.0 # self.__MAX_CCW_PW = 1720 µS
        __PW = __MIN_PW # Start from shortest to longest!

        __SAMPLE_TIME_PER_PW = 0.5 # In seconds, time interval to change the servo speed
        __timeMilestone = time.time()

        while __PW <= __MAX_PW:
            if __PW is not self.__pi.get_servo_pulsewidth(self.controlPin): # Only apply changes when needed
                self.__pi.set_servo_pulsewidth(self.controlPin, __PW)

            # I guess I should gather feedback signal samples around here
            # I have another class to do so. I mean, a method that returns the read of a PWM signal and I successfully tested it working.

            if (time.time() - __timeMilestone >= __SAMPLE_TIME_PER_PW): # Blink-without-delay.ino reference ;)
                __timeMilestone = time.time()
                __PW += __PW_STEP # Increase PWM control signal for next iteration!
```

Any ideas on how to deal with this? I'm stuck here however I feel I am so close. The main problem I think it is that I lack of understanding a part of the concept well enough so I can not translate the next step to code.

Should I gather as many samples as I can on that window time? And then what? Since the value will iterate from 2.9% to 97.1% several times (Or maybe none if the servo is slow enough) how can I measure there a speed change?

Thanks in advance! Sorry for long question,

Cheers.

Body:
I'm working on a project with a Raspberry Pi and a Parallax 360 servo widh feedback and pigpio library. What I'm trying to accomplish is to determine programatically the min and max pulse width I could send to the servo in both rotation directions.

These values are shown in the servo's datasheet, however I would like to code a "calibrate" function since this absolute values might vary a little from unit to unit, as I verified with my classmates'. (BTW, minimum PW is 1280 µS for max speed in one direction whereas maximum PW is 1720 µS for max speed in the opposite direction, where around 1500 µS means 0 RPM)

The feedback signal is also documented on said datasheet, and I am able to read it. It is also a PWM signal which will vary from 2.9% to 97.1% duty cycle depending on the shaft angle. I thought that if I'm able to gather samples of this signal in a given window of time, I would be able to calculate how quickly it's spinning at different control signals.

Assuming that the servo speed is constant at a constant control signal, changes on this "rate" or "slope" for the feedback duty cycle signal, will indicate that the servo is accelerating or decelerating. Cool. This is the procedure I thought to find the limits:

Start below the absolute minimum (1280 µS) where the servo will spin at its maximum speed, and start increasing the duty cycle of the control signal until I can detect a deceleration on the feedback signal, indicating that I found the real minimum control PW.

Continue increasing the duty cycle of the control signal, until the "slope" is zero, which means the servo stopped and I found the next bound.

Continue increasing the duty cycle of the control signal, until I detect and acceleration on the feedback signal which will indicate the servo started to move again (In the opposite direction, OFC)

Continue increasing the duty cycle of the control signal, observing the acceleration "slope" until this slope is zero, which means the servo have reached its maximum speed.

The problem... I don't really have a clue on the maths involved or needed to calculate this. This is my code by now (This is a method part of the class I'm coding meant to control the servo):

Thanks @101 about the issue of variables' name. Before this I was coding the class itself and thus the confusing naming. Do not take that on consideration!

    def calibrate(self):
        __PW_STEP = 10 # Pulse width increasing step
        __MIN_PW = self.__MAX_CW_PW - 100.0 # self.__MAX_CW_PW = 1280 µS
        __MAX_PW = self.__MAX_CCW_PW + 100.0 # self.__MAX_CCW_PW = 1720 µS
        __PW = __MIN_PW # Start from shortest to longest!

        __SAMPLE_TIME_PER_PW = 0.5 # In seconds, time interval to change the servo speed
        __timeMilestone = time.time()

        while __PW <= __MAX_PW:
            if __PW is not self.__pi.get_servo_pulsewidth(self.controlPin): # Only apply changes when needed
                self.__pi.set_servo_pulsewidth(self.controlPin, __PW)

            # I guess I should gather feedback signal samples around here
            # I have another class to do so. I mean, a method that returns the read of a PWM signal and I successfully tested it working.

            if (time.time() - __timeMilestone >= __SAMPLE_TIME_PER_PW): # Blink-without-delay.ino reference ;)
                __timeMilestone = time.time()
                __PW += __PW_STEP # Increase PWM control signal for next iteration!

Any ideas on how to deal with this? I'm stuck here however I feel I am so close. The main problem I think it is that I lack of understanding a part of the concept well enough so I can not translate the next step to code.

Should I gather as many samples as I can on that window time? And then what? Since the value will iterate from 2.9% to 97.1% several times (Or maybe none if the servo is slow enough) how can I measure there a speed change?

Thanks in advance! Sorry for long question,

Cheers.


问:
App recording only caller voice in android 12
I have built a call recorder app , i have tested the app in android 9 and it does record both sides but when i try to make a call with one plus phone which has android 12 , it does only record my voice not the other side voice , is there any special permission to be granted or something cause i'm alread using the accessibility permission to handle this , any help would be appreciated thank you

Recording block code

```<code>      RecordingThread(Context context, String mode, Recorder recorder) throws RecordingException {
        this.context = context;
        channels = (mode.equals(Recorder.MONO) ? 1 : 2);
        this.recorder = recorder;
        bufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE, channels == 1 ?
                        AudioFormat.CHANNEL_IN_MONO : AudioFormat.CHANNEL_IN_STEREO,
                AudioFormat.ENCODING_PCM_16BIT);
        audioRecord = createAudioRecord();
        audioRecord.startRecording();
    }

</code>```

Permissions in manifest

```<code>
   <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="com.google.android.finsky.permission.BIND_GET_INSTALL_REFERRER_SERVICE" />
    <uses-permission android:name="android.permission.READ_CALL_LOG" />
    <uses-permission android:name="android.permission.WRITE_CALL_LOG" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
    <uses-permission
        android:name="android.permission.CAPTURE_AUDIO_OUTPUT"
        tools:ignore="ProtectedPermissions" />
    <uses-permission
        android:name="android.permission.WRITE_SECURE_SETTINGS"
        tools:ignore="ProtectedPermissions" />
    <uses-permission
        android:name="android.permission.WRITE_SETTINGS"
        tools:ignore="ProtectedPermissions" />
    <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
    <uses-permission android:name="com.google.android.gms.permission.AD_ID" />
</code>```

Body:
I have built a call recorder app , i have tested the app in android 9 and it does record both sides but when i try to make a call with one plus phone which has android 12 , it does only record my voice not the other side voice , is there any special permission to be granted or something cause i'm alread using the accessibility permission to handle this , any help would be appreciated thank you

Recording block code

      RecordingThread(Context context, String mode, Recorder recorder) throws RecordingException {
        this.context = context;
        channels = (mode.equals(Recorder.MONO) ? 1 : 2);
        this.recorder = recorder;
        bufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE, channels == 1 ?
                        AudioFormat.CHANNEL_IN_MONO : AudioFormat.CHANNEL_IN_STEREO,
                AudioFormat.ENCODING_PCM_16BIT);
        audioRecord = createAudioRecord();
        audioRecord.startRecording();
    }

Permissions in manifest

   <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="com.google.android.finsky.permission.BIND_GET_INSTALL_REFERRER_SERVICE" />
    <uses-permission android:name="android.permission.READ_CALL_LOG" />
    <uses-permission android:name="android.permission.WRITE_CALL_LOG" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
    <uses-permission
        android:name="android.permission.CAPTURE_AUDIO_OUTPUT"
        tools:ignore="ProtectedPermissions" />
    <uses-permission
        android:name="android.permission.WRITE_SECURE_SETTINGS"
        tools:ignore="ProtectedPermissions" />
    <uses-permission
        android:name="android.permission.WRITE_SETTINGS"
        tools:ignore="ProtectedPermissions" />
    <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
    <uses-permission android:name="com.google.android.gms.permission.AD_ID" />


问:
How to make a DIV not breakable with CSS in printable page?
I have some div containers that have some content  inside them, when they reach a specific height the break to a new column, here the content of the div are breaking so some content stay in column 1 and others content go to column 2 . I do not want that , I want all the content of the div go to the column 2.

It works normally on the html page but when I try to print it, it doesent work

`

```<code>.grade-table is the main containers
.grade is the div I'm talking about
</code>```

CSS

```<code>  .grade-table{
    margin-top: 20px;
    column-count: 2;
    column-fill: auto;
    height: 400px;
  }
  .grade-table .grade{
  overflow: auto;
  }
</code>```
```<code>

</code>```

Body:
I have some div containers that have some content  inside them, when they reach a specific height the break to a new column, here the content of the div are breaking so some content stay in column 1 and others content go to column 2 . I do not want that , I want all the content of the div go to the column 2.

It works normally on the html page but when I try to print it, it doesent work

`

.grade-table is the main containers
.grade is the div I'm talking about

CSS

  .grade-table{
    margin-top: 20px;
    column-count: 2;
    column-fill: auto;
    height: 400px;
  }
  .grade-table .grade{
  overflow: auto;
  }


问:
Upload an image with Postman, working on the desktop app but not on the browser
I'm building an app, that including service to upload images to S3 AWS, important to say that the bucket "NOT PUBLIC".

When I'm sending the request through the Postman desktop app, I'm getting 200OK...
BUT, when I'm sending the request through the Postman browser, I'm getting 500 error.
I tried with all the types of "Content-type", and I also tried to unmark the content type, it doesn't work...
Errors:
1)

```<code>"message": "Failed to parse multipart servlet request; nested exception is javax.servlet.ServletException: org.apache.tomcat.util.http.fileupload.impl.InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is application/json"
</code>```

(If I unmark the "Content type")

```<code>"message": "Content type 'application/octet-stream' not supported"
</code>```

If I'm inserting "multipart/fromdata"

```<code>"message": "Failed to parse multipart servlet request; nested exception is java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found"
</code>```

Yes, and also tried with the boundary in the content type :)

Here is the code of the controller:

```<code>package com.package

import com.package.ImageDTO;
import com.package.model.DeletedImageDTO;
import com.package.service.ImageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * Control's endPoints for authentication
 */
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
@Slf4j
public class ImageController extends ValidationExceptionHandler {

    private final ImageService imageService;

    @GetMapping("/user/image")
    public ResponseEntity<List<ImageDTO>> getUserImages() {
        final List<ImagesDTO> allUserImages = imageService.getAllUserImages();
        return ResponseEntity.status(HttpStatus.OK).body(allUserImages);
    }

    @PostMapping(value = "/user/images", consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE})
    public ResponseEntity<List<ImageDTO>> saveUserImages(@RequestPart(name = "imageDTOS") ImageDTO[] imageDTOS,
                                                                     @RequestPart(name = "deletedImageDTOs") DeletedImageDTO[] deletedImageDTOs,
                                                                     MultipartHttpServletRequest request) throws IOException {
        final List<ImageDTO> imageDTOSResponse = imageService.saveUserImages(Arrays.stream(imageDTOS).toList(),
                Arrays.stream(deletedImageDTOs).toList(), request);

        return ResponseEntity.status(HttpStatus.OK).body(imageDTOSResponse);
    }

    @DeleteMapping("/user/images/{id}")
    public ResponseEntity<Void> deleteUserImage(@PathVariable(name = "id") final Long id) {
        imageService.deleteImages(id);
        return ResponseEntity.noContent().build();
    }
}

</code>```

The language of the backend is: Java, Spring boot

Everything has been mentioned above.

Body:
I'm building an app, that including service to upload images to S3 AWS, important to say that the bucket "NOT PUBLIC".

When I'm sending the request through the Postman desktop app, I'm getting 200OK...
BUT, when I'm sending the request through the Postman browser, I'm getting 500 error.
I tried with all the types of "Content-type", and I also tried to unmark the content type, it doesn't work...
Errors:
1)

"message": "Failed to parse multipart servlet request; nested exception is javax.servlet.ServletException: org.apache.tomcat.util.http.fileupload.impl.InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is application/json"

(If I unmark the "Content type")

"message": "Content type 'application/octet-stream' not supported"

If I'm inserting "multipart/fromdata"

"message": "Failed to parse multipart servlet request; nested exception is java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found"

Yes, and also tried with the boundary in the content type :)

Here is the code of the controller:

package com.package

import com.package.ImageDTO;
import com.package.model.DeletedImageDTO;
import com.package.service.ImageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * Control's endPoints for authentication
 */
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
@Slf4j
public class ImageController extends ValidationExceptionHandler {

    private final ImageService imageService;

    @GetMapping("/user/image")
    public ResponseEntity<List<ImageDTO>> getUserImages() {
        final List<ImagesDTO> allUserImages = imageService.getAllUserImages();
        return ResponseEntity.status(HttpStatus.OK).body(allUserImages);
    }

    @PostMapping(value = "/user/images", consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE})
    public ResponseEntity<List<ImageDTO>> saveUserImages(@RequestPart(name = "imageDTOS") ImageDTO[] imageDTOS,
                                                                     @RequestPart(name = "deletedImageDTOs") DeletedImageDTO[] deletedImageDTOs,
                                                                     MultipartHttpServletRequest request) throws IOException {
        final List<ImageDTO> imageDTOSResponse = imageService.saveUserImages(Arrays.stream(imageDTOS).toList(),
                Arrays.stream(deletedImageDTOs).toList(), request);

        return ResponseEntity.status(HttpStatus.OK).body(imageDTOSResponse);
    }

    @DeleteMapping("/user/images/{id}")
    public ResponseEntity<Void> deleteUserImage(@PathVariable(name = "id") final Long id) {
        imageService.deleteImages(id);
        return ResponseEntity.noContent().build();
    }
}

The language of the backend is: Java, Spring boot

Everything has been mentioned above.


问:
Retrieve diff with 0 context lines using GitHub API in Python
I'm trying to find a way to retrieve a diff with 0 context files using the GitHub API. I've tried to use the following request:

```<code>requests.get('https://git.{org_name}.com/api/v3/repos/{OWNER}/{repo}/pulls/34623?context=0', headers=headers)
</code>```

But unfortunately I still get the standard 3 lines of context. What I am trying to achieve is the same result as if I'm using the git diff -U0 command locally.

Is there any way I can accomplish by only using the requests module in Python?

Body:
I'm trying to find a way to retrieve a diff with 0 context files using the GitHub API. I've tried to use the following request:

requests.get('https://git.{org_name}.com/api/v3/repos/{OWNER}/{repo}/pulls/34623?context=0', headers=headers)

But unfortunately I still get the standard 3 lines of context. What I am trying to achieve is the same result as if I'm using the git diff -U0 command locally.

Is there any way I can accomplish by only using the requests module in Python?


问:
How to Render React router-dom Switch
I am working on ReactJS project, Now I have render routes based on API response if the API returns user type User then I have to render user routes. Otherwise I have to render Admin routes and a 404 page.

function Index() {
    const userType = "user" // fetching this data from Api

    if (userType === "user")
        return (
          <Switch>
              <Route path="/" exact>
                  <User/>
              </Route>
          </Switch>
        )
    else
        return (
          <Switch>
              <Route path="/" exact>
                  <Admin/>
              </Route>
          </Switch>
        )
}
```

Title: How to Render React router-dom Switch


问:
How do I make the center of rotation of this '::before' pseudoelement change?
I'm trying to make an animated border for a div. I unhid the overflow of its formatting element so that I could see what the issue was. I'd like to make the center of rotation the center of the larger div.

I know I can make the center of rotation higher by setting the width and height of the before psuedoelement to that of its container, but I want to make it taller because if I set the width and height to its formatting element, it's too small and doesn't cover the edges.

I've tried using CSS positioning, but it isn't working and I have no idea why.

```<code>        <div class="center">
        <div class="wrapper">
            <div class="directory module">
                <div id="header" class="small_wrapper center">
                    <div class="module">
                        <p style="font-size: 22px">Placeholder</p>
                      </div>
                </div>
                <div class="directory_bar small_wrapper center"><div class="module">About Me</div></div>
                <div class="directory_bar small_wrapper center"><div class="module">PC Builds</div></div>
                <div class="directory_bar small_wrapper center"><div class="module">Original Characters</div></div>
                <div class="directory_bar small_wrapper center"><div class="module">Games & Loadouts</div></div>
                <div class="directory_bar small_wrapper center"><div class="module">Socials</div></div>
            </div>
        </div>
    </div>

@charset "utf-8";

@keyframes rotate {
    0% {
      transform: rotate(0);
    }

    50% {
        transform: rotate(180deg);
    }

    100% {
        transform: rotate(360deg);
    }
}

html {
    font-size: 3.0vh;
}

body {
    background-color: #2C2C2C;
    font-family: Urbanist, sans serif;
    color: white;
}

p {
    margin: 0;
}

.left, .right, .center {
    position: relative;
}

.center {
    margin-left: auto;
    margin-right: auto;
}

.module {
    background-color:#2C2C2C;
    text-align: center;
    padding: 10px;

    border-radius: 18px;
    z-index: 1000;
    position: relative;
}

.wrapper, .small_wrapper {
    position: relative;
    width: fit-content;
    height: fit-content;
    background: blue;
    z-index: 1000;

}

.wrapper {
    border-radius: 20px;
    padding: 4px;
}

.wrapper::before {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left:  0;
    background: linear-gradient(to right, rgb(255, 0, 0), rgb(145,
    255, 0), rgb(189, 1, 180));
    animation: rotate;
    animation-duration: 3s;
    animation-iteration-count: infinite;
    animation-timing-function: linear;
    content: '';
    border-radius: 20px;
    height: 1000px;

}

.small_wrapper {
    padding: 3px;
}

.directory_bar {
    margin-top: 5vh;
}

.directory {
    padding: 5vh;
}

.center > .wrapper {
    margin-left: 100px;
}

.directory_bar, #header {
    border-radius: 8px;
}

.directory_bar > .module, #header > .module {
    border-radius: 7px;
}
</code>```

Body:
I'm trying to make an animated border for a div. I unhid the overflow of its formatting element so that I could see what the issue was. I'd like to make the center of rotation the center of the larger div.

I know I can make the center of rotation higher by setting the width and height of the before psuedoelement to that of its container, but I want to make it taller because if I set the width and height to its formatting element, it's too small and doesn't cover the edges.

I've tried using CSS positioning, but it isn't working and I have no idea why.

Placeholder

About Me

PC Builds

Original Characters

Games & Loadouts

Socials

@charset "utf-8";

@keyframes rotate {
    0% {
      transform: rotate(0);
    }

    50% {
        transform: rotate(180deg);
    }

    100% {
        transform: rotate(360deg);
    }
}

html {
    font-size: 3.0vh;
}

body {
    background-color: #2C2C2C;
    font-family: Urbanist, sans serif;
    color: white;
}

p {
    margin: 0;
}

.left, .right, .center {
    position: relative;
}

.center {
    margin-left: auto;
    margin-right: auto;
}

.module {
    background-color:#2C2C2C;
    text-align: center;
    padding: 10px;

    border-radius: 18px;
    z-index: 1000;
    position: relative;
}

.wrapper, .small_wrapper {
    position: relative;
    width: fit-content;
    height: fit-content;
    background: blue;
    z-index: 1000;

}

.wrapper {
    border-radius: 20px;
    padding: 4px;
}

.wrapper::before {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left:  0;
    background: linear-gradient(to right, rgb(255, 0, 0), rgb(145,
    255, 0), rgb(189, 1, 180));
    animation: rotate;
    animation-duration: 3s;
    animation-iteration-count: infinite;
    animation-timing-function: linear;
    content: '';
    border-radius: 20px;
    height: 1000px;

}

.small_wrapper {
    padding: 3px;
}

.directory_bar {
    margin-top: 5vh;
}

.directory {
    padding: 5vh;
}

.center > .wrapper {
    margin-left: 100px;
}

.directory_bar, #header {
    border-radius: 8px;
}

.directory_bar > .module, #header > .module {
    border-radius: 7px;
}


问:
How can I receive and send multiple messages with PHP sockets?
I am just playing with PHP sockets for fun. I am trying to implement a messaging service. I've been able to connect multiple client to the server but I can't receive all of the messages that I'm expecting.

my server.php

```<code><?php
set_time_limit(0);

$address = '127.0.0.1';

$port = 8000;

$server = socket_create(AF_INET, SOCK_STREAM, 0);
$bind = socket_bind($server, $address, $port);

$clients = [];
$i = 0;

socket_listen($server);

while(TRUE) {
  foreach($clients as $id => $client) {
    $input = socket_read($client, 1024);

    if($input) {
      echo $input."\r\n";

      socket_write($client, 'We got your message.');
    }
  }

  $clients[$i] = socket_accept($server);

  if($clients[$i]) {
    echo 'Connection established.'."\r\n";

    socket_write($clients[$i], 'Welcome to the server!');
    $i++;
  } else {
    unset($clients[$i]);
  }
}
</code>```

my client.php

```<code><?php
$host = '127.0.0.1';
$port = 8000;
$timeout = 3;

$server = socket_create(AF_INET, SOCK_STREAM, 0);
socket_connect($server, $host, $port);

//socket_write($socket, 'Hello');

$result = socket_read($server, 1024);

echo 'Reply From Server: '.$result."\r\n";
$i = 0;

while($i <= 5) {
  sleep(3);

  socket_write($server, 'Hi server! Im Client 1');

  $result = socket_read($server, 1024);

  echo 'Reply From Server: '.$result.' ';

  echo $i."\r\n";
  $i++;
}

socket_close($server);
</code>```

And also I have a client2.php file which exactly same with client.php except socket_write($server, 'Hi server! Im Client 1'); this line. Instead is says Im Client 2.

What am I expecting is when I run these 3 from seperate terminal windows is something like this;

Connection established.

Hi server! Im Client 1

Connection established.

Hi server! Im Client 1

Hi server! Im Client 2

Hi server! Im Client 1

Hi server! Im Client 2

Hi server! Im Client 1

Hi server! Im Client 2

Hi server! Im Client 1

Hi server! Im Client 2

Hi server! Im Client 2

And there must be 3 seconds between each block if we think like I run both of 3 at the same time.

But instead I am getting this:

Connection established.

Hi server! Im Client 1

Connection established.

Hi server! Im Client 1

Hi server! Im Client 2

And another problem is clients should be terminated themselves but they're not. Their outputs are like following:

client.php

Reply From Server: Welcome to the server!

Reply From Server: We got your message. 0

Reply From Server: We got your message. 1

client2.php

Reply From Server: Welcome to the server!

Reply From Server: We got your message. 0

I was expecting exact number of messages but I can't get.

Body:
I am just playing with PHP sockets for fun. I am trying to implement a messaging service. I've been able to connect multiple client to the server but I can't receive all of the messages that I'm expecting.

my server.php

<?php
set_time_limit(0);

$address = '127.0.0.1';

$port = 8000;

$server = socket_create(AF_INET, SOCK_STREAM, 0);
$bind = socket_bind($server, $address, $port);

$clients = [];
$i = 0;

socket_listen($server);

while(TRUE) {
  foreach($clients as $id => $client) {
    $input = socket_read($client, 1024);

    if($input) {
      echo $input."\r\n";

      socket_write($client, 'We got your message.');
    }
  }

  $clients[$i] = socket_accept($server);

  if($clients[$i]) {
    echo 'Connection established.'."\r\n";

    socket_write($clients[$i], 'Welcome to the server!');
    $i++;
  } else {
    unset($clients[$i]);
  }
}

my client.php

<?php
$host = '127.0.0.1';
$port = 8000;
$timeout = 3;

$server = socket_create(AF_INET, SOCK_STREAM, 0);
socket_connect($server, $host, $port);

//socket_write($socket, 'Hello');

$result = socket_read($server, 1024);

echo 'Reply From Server: '.$result."\r\n";
$i = 0;

while($i <= 5) {
  sleep(3);

  socket_write($server, 'Hi server! Im Client 1');

  $result = socket_read($server, 1024);

  echo 'Reply From Server: '.$result.' ';

  echo $i."\r\n";
  $i++;
}

socket_close($server);

And also I have a client2.php file which exactly same with client.php except socket_write($server, 'Hi server! Im Client 1'); this line. Instead is says Im Client 2.

What am I expecting is when I run these 3 from seperate terminal windows is something like this;

Connection established.

Hi server! Im Client 1

Connection established.

Hi server! Im Client 1

Hi server! Im Client 2

Hi server! Im Client 1

Hi server! Im Client 2

Hi server! Im Client 1

Hi server! Im Client 2

Hi server! Im Client 1

Hi server! Im Client 2

Hi server! Im Client 2

And there must be 3 seconds between each block if we think like I run both of 3 at the same time.

But instead I am getting this:

Connection established.

Hi server! Im Client 1

Connection established.

Hi server! Im Client 1

Hi server! Im Client 2

And another problem is clients should be terminated themselves but they're not. Their outputs are like following:

client.php

Reply From Server: Welcome to the server!

Reply From Server: We got your message. 0

Reply From Server: We got your message. 1

client2.php

Reply From Server: Welcome to the server!

Reply From Server: We got your message. 0

I was expecting exact number of messages but I can't get.


问:
Android ADB simultaneous input taps
I am doing some testing on Android related to screen pinning. I want to send simultaneous input taps on a device on the back button and the overview button to stop screen pinning.

I tried to do this and put the second input has a delay.

```<code>adb shell "input tap X1 Y1 ; input tap X2 Y2"
</code>```

How do I make two input taps simultaneous ?

Title: Android ADB simultaneous input taps

Body:
I am doing some testing on Android related to screen pinning. I want to send simultaneous input taps on a device on the back button and the overview button to stop screen pinning.

I tried to do this and put the second input has a delay.

adb shell "input tap X1 Y1 ; input tap X2 Y2"

How do I make two input taps simultaneous ?


问:
Form - symfony 5.4 - What type of field for Player
Class Presence

```<code>    /**
     * @ORM\ManyToOne(targetEntity=Player::class, inversedBy="presence")
     * @ORM\JoinColumn(name="player_id", referencedColumnName="id", onDelete="CASCADE", nullable=false)
     */
    private $player;
</code>```

PresenceType

```<code>...
 $builder
            ->add('player', ChoiceType::class, [
                'expanded'      => true,
                'multiple'      => true,
                'choices'       => $players,
                'choice_value'  => function($player){
                    return $player->getId();
                },
                'choice_label'  => function($player) {
                    return $player->getNom();
                },
            ])
            ->add('duration', ChoiceType::class, [
                'choices' => [
                    '15 min'    => 15,
                    '30 min'    => 30,
                ],
            ])
        ;
</code>```

Here is my problem. Until now, the "player" field had:

expanded: false

many: false

Everything was working normally

Now I want to pass

expanded: true

multiple: true

I have the following error message appearing because the player field is expecting a Player object and I am passing an array (multiple=true)

But I don't know what type of field to assign to player

Expected argument of type "App\Entity\Player or null", "array" given at property path "player".

Do you have an example ?

Body:
Class Presence

    /**
     * @ORM\ManyToOne(targetEntity=Player::class, inversedBy="presence")
     * @ORM\JoinColumn(name="player_id", referencedColumnName="id", onDelete="CASCADE", nullable=false)
     */
    private $player;

PresenceType

...
 $builder
            ->add('player', ChoiceType::class, [
                'expanded'      => true,
                'multiple'      => true,
                'choices'       => $players,
                'choice_value'  => function($player){
                    return $player->getId();
                },
                'choice_label'  => function($player) {
                    return $player->getNom();
                },
            ])
            ->add('duration', ChoiceType::class, [
                'choices' => [
                    '15 min'    => 15,
                    '30 min'    => 30,
                ],
            ])
        ;

Here is my problem. Until now, the "player" field had:

expanded: false

many: false

Everything was working normally

Now I want to pass

expanded: true

multiple: true

I have the following error message appearing because the player field is expecting a Player object and I am passing an array (multiple=true)

But I don't know what type of field to assign to player

Expected argument of type "App\Entity\Player or null", "array" given at property path "player".

Do you have an example ?


问:
Accessing Odoo on my NAS with docker and portainer from external internet
I have installed Odoo on my NAS with Docker and Portainer.

I can access the Odoo with localhost in my office, eg, http://0.0.0.0:port.
I would like to know how to access with external internet, for example in my home?

Any ideas?


问:
How can I change elements position in a JS list?
I was trying to sort (based on dates) the elements in an array using the insertion sort algorithm, I think the problem is due to the nature of the element in the list, because when it comes to var x = A[i] or (outside the while) A[j + 1] = x the programme crashes and the Chrome console gives back

```<code>Uncaught TypeError: Failed to set an indexed property on HTMLCollection: Indexed property setter is not supported.
</code>```

I'm new to JS so don't be ruthless to me
Here's my code:

```<code>function insertion_sort(A) {
        var len = A.length;
        var i = 1;
        while (i < len) {
            var x = A[i];
            var j = i - 1;
            while (j >= 0 && dayjs(A[j].querySelector('span').innerText).format('YYYY-MM-DD') > dayjs(x.querySelector('span').innerText).format('YYYY-MM-DD')) {
                A[j + 1] = A[j];
                j = j - 1;
            }
            A[j + 1] = x;
            i = i + 1;
        }
        console.log(A);
    }

    let posts = [];

    posts = document.getElementsByTagName('article');

    insertion_sort(posts);
</code>```

Body:
I was trying to sort (based on dates) the elements in an array using the insertion sort algorithm, I think the problem is due to the nature of the element in the list, because when it comes to var x = A[i] or (outside the while) A[j + 1] = x the programme crashes and the Chrome console gives back

Uncaught TypeError: Failed to set an indexed property on HTMLCollection: Indexed property setter is not supported.

I'm new to JS so don't be ruthless to me
Here's my code:

function insertion_sort(A) {
        var len = A.length;
        var i = 1;
        while (i < len) {
            var x = A[i];
            var j = i - 1;
            while (j >= 0 && dayjs(A[j].querySelector('span').innerText).format('YYYY-MM-DD') > dayjs(x.querySelector('span').innerText).format('YYYY-MM-DD')) {
                A[j + 1] = A[j];
                j = j - 1;
            }
            A[j + 1] = x;
            i = i + 1;
        }
        console.log(A);
    }

    let posts = [];

    posts = document.getElementsByTagName('article');

    insertion_sort(posts);


问:
Paste special in spreadsheets
How is paste special used in spreadsheets?

I tried copying a substring from a column to make a new separate columns of sub strings. Now how would I delete the original column?

Title: Paste special in spreadsheets


问:
Using RF Modules with Raspberry Pi Pico
I have 2 Raspberry Pi Picos running MicroPython. I am trying to use a 433 MHz RF transmitter on one Pico and a 433 MHz RF receiver on the other Pico. I am currently using UART to transmit and receive data:

```<code># Receiver

import os
import machine
from time import sleep

uart = machine.UART(0, 4800)
print(uart)

led = machine.Pin(25, machine.Pin.OUT)

b = None
msg = ""

while True:
    if uart.any():
        b = uart.readline()
        try:
            msg = b.decode('utf-8')
            print(str(msg))
        except:
            print("Failed (" + str(type(b)) + "): " + str(b))
            pass

    led.toggle()
    sleep(1)
</code>```

and

```<code># Transmitter

import os
import machine
from time import sleep

uart = machine.UART(0, 4800)
print(uart)

led = machine.Pin(25, machine.Pin.OUT)

while True:
    sleep(5)
    led.toggle()
    uart.write('Hello, World!')
</code>```

But the receiver prints stuff like this even when the transmitter is not transmitting. (I can't paste it here as it messes with the formatting)

As an experiment, I connected the TX on one Pico to the RX of the other pico, and it was able to send the data successfully. Therefore, I believe it is the transmitter and receiver getting interference from other signals.

My Question:

Arduino has libraries for packet radio. (see this) Is there anything similar in MicroPython or for the Raspberry Pi Pico?

Thanks.

Title: Using RF Modules with Raspberry Pi Pico

Body:
I have 2 Raspberry Pi Picos running MicroPython. I am trying to use a 433 MHz RF transmitter on one Pico and a 433 MHz RF receiver on the other Pico. I am currently using UART to transmit and receive data:

# Receiver

import os
import machine
from time import sleep

uart = machine.UART(0, 4800)
print(uart)

led = machine.Pin(25, machine.Pin.OUT)

b = None
msg = ""

while True:
    if uart.any():
        b = uart.readline()
        try:
            msg = b.decode('utf-8')
            print(str(msg))
        except:
            print("Failed (" + str(type(b)) + "): " + str(b))
            pass

    led.toggle()
    sleep(1)

and

# Transmitter

import os
import machine
from time import sleep

uart = machine.UART(0, 4800)
print(uart)

led = machine.Pin(25, machine.Pin.OUT)

while True:
    sleep(5)
    led.toggle()
    uart.write('Hello, World!')

But the receiver prints stuff like this even when the transmitter is not transmitting. (I can't paste it here as it messes with the formatting)

As an experiment, I connected the TX on one Pico to the RX of the other pico, and it was able to send the data successfully. Therefore, I believe it is the transmitter and receiver getting interference from other signals.

My Question:

Arduino has libraries for packet radio. (see this) Is there anything similar in MicroPython or for the Raspberry Pi Pico?

Thanks.


问:
ModuleNotFoundError: No module named 'flask._compat'
I have a problem with a script. When I run python migration.py db init in terminal I get: ModuleNotFoundError: No module named 'flask._compat'. I'm use python 3.7.5. This is my requirement.txt file:

```<code>Flask==2.1.0
Flask-Migrate==2.5.3
Flask-Script==2.0.6
mysql-connector-python==8.0.5
Flask-SQLAlchemy==2.4.4
gunicorn==20.0.4
psycopg2-binary==2.8.6
marshmallow==3.7.1
</code>```

and this is my migrations.py script

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://root:root@flask-db/users'

db = SQLAlchemy(app)
migrate = Migrate(app, db)
handler = Manager(app)

class Users(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(128))

    surname = db.Column(db.String(128))
    identity_number = db.Column(db.Integer)

if __name__ == '__main__':
    handler.run()
```

How do I solve this problem without manually creating database, with the help of a script in terminal. For example Python migrations.py db init, then same with migrate option, and upgrade?

Body:
I have a problem with a script. When I run python migration.py db init in terminal I get: ModuleNotFoundError: No module named 'flask._compat'. I'm use python 3.7.5. This is my requirement.txt file:

Flask==2.1.0
Flask-Migrate==2.5.3
Flask-Script==2.0.6
mysql-connector-python==8.0.5
Flask-SQLAlchemy==2.4.4
gunicorn==20.0.4
psycopg2-binary==2.8.6
marshmallow==3.7.1

and this is my migrations.py script

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://root:root@flask-db/users'

db = SQLAlchemy(app)
migrate = Migrate(app, db)
handler = Manager(app)

class Users(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(128))

    surname = db.Column(db.String(128))
    identity_number = db.Column(db.Integer)

if __name__ == '__main__':
    handler.run()

How do I solve this problem without manually creating database, with the help of a script in terminal. For example Python migrations.py db init, then same with migrate option, and upgrade?


问:
Failed spring boot app with java.lang.NoSuchMethodError: java.util.List.of
facing NoSuchMethodError, when I run my spring boot(v2.7.2) build jar file on my cmd. It's works fine on Eclipse IDE

```<code>@Override
public void run(String... args) throws Exception {

        try {
            Role role1 = new Role();
            role1.setId(AppConstants.ADMIN_USER);
            role1.setName("ROLE_ADMIN");

            Role role2 = new Role();
            role2.setId(AppConstants.NORMAL_USER);
            role2.setName("ROLE_NORMAL");

            List<Role> roles = List.of(role1, role2); //@line 50

            List<Role> result = this.roleRepo.saveAll(roles);

            result.forEach(r -> System.out.println(r.getName()));

        } catch (Exception e) {

            e.printStackTrace();
        }
</code>```

Body:
facing NoSuchMethodError, when I run my spring boot(v2.7.2) build jar file on my cmd. It's works fine on Eclipse IDE

@Override
public void run(String... args) throws Exception {

        try {
            Role role1 = new Role();
            role1.setId(AppConstants.ADMIN_USER);
            role1.setName("ROLE_ADMIN");

            Role role2 = new Role();
            role2.setId(AppConstants.NORMAL_USER);
            role2.setName("ROLE_NORMAL");

            List<Role> roles = List.of(role1, role2); //@line 50

            List<Role> result = this.roleRepo.saveAll(roles);

            result.forEach(r -> System.out.println(r.getName()));

        } catch (Exception e) {

            e.printStackTrace();
        }


问:
"The expression is unused" error when passing { navController.navigate } multiple times [Kotlin]
I've keep getting a "The expression is unused" error. I've been trying to pass the navController.navigate() through my HomeScreen composable to my SearchBar composable.

@Composable
fun App(){
    val navController = rememberNavController()
    NavHost(navController = navController, startDestination = "home") {
        composable("home")   { HomeScreen(onNavigateToSearch = { navController.navigate("search")},) }
        composable("search") { SearchScreen() }
    }
}

@Composable
fun HomeScreen(onNavigateToSearch: () -> Unit, ) {
    Column { SearchBar(onNavigateToSearch = onNavigateToSearch ) }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SearchBar(
    searchState: MutableState<TextFieldValue> = remember { mutableStateOf(TextFieldValue()) },
    onNavigateToSearch: () -> Unit,
) {
    TextField(
        value = searchState.value,
        onValueChange = { searchState.value = it},
        keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search,),
        // ERROR HAPPENS ON THE LINE BELOW
        keyboardActions = KeyboardActions(onSearch = { onNavigateToSearch }),
    )
}
```

I expected the navController.navigate() to be activated when the onSearch action completes.

Body:
I've keep getting a "The expression is unused" error. I've been trying to pass the navController.navigate() through my HomeScreen composable to my SearchBar composable.

@Composable
fun App(){
    val navController = rememberNavController()
    NavHost(navController = navController, startDestination = "home") {
        composable("home")   { HomeScreen(onNavigateToSearch = { navController.navigate("search")},) }
        composable("search") { SearchScreen() }
    }
}

@Composable
fun HomeScreen(onNavigateToSearch: () -> Unit, ) {
    Column { SearchBar(onNavigateToSearch = onNavigateToSearch ) }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SearchBar(
    searchState: MutableState<TextFieldValue> = remember { mutableStateOf(TextFieldValue()) },
    onNavigateToSearch: () -> Unit,
) {
    TextField(
        value = searchState.value,
        onValueChange = { searchState.value = it},
        keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search,),
        // ERROR HAPPENS ON THE LINE BELOW
        keyboardActions = KeyboardActions(onSearch = { onNavigateToSearch }),
    )
}

I expected the navController.navigate() to be activated when the onSearch action completes.


问:
Why does the MASM symbol RAX return true for both IFDEF and IFNDEF?
Recently was working on a project to include 64-bit code when assembled under ML64.exe. However, this code actually included the 32-bit MASM directives, so the build failed.

```<code>IFNDEF RAX

.686P
.MODEL FLAT,STDCALL
OPTION CASEMAP:NONE
OPTION PROLOGUE:W32Prologue

ELSE

OPTION CASEMAP:NONE
OPTION PROLOGUE:W64Prologue
OPTION EPILOGUE:NONE

ENDIF
</code>```

The fix was to change IFNDEF RAX to IFDEF RAX as follows

```<code>IFDEF RAX

OPTION CASEMAP:NONE
OPTION PROLOGUE:W64Prologue
OPTION EPILOGUE:NONE

ELSE

.686P
.MODEL FLAT,STDCALL
OPTION CASEMAP:NONE
OPTION PROLOGUE:W32Prologue

ENDIF
</code>```

Wrote a simple example to show why using IFNDEF RAX is misleading

rax.asm

```<code>option casemap:none

extrn printf:proc

.data

     szRAX db 'Symbol RAX exists',0ah,0

.code

main proc

     ifdef   RAX
     mov     rcx,offset szRAX
     call    printf
     endif

     ifndef  RAX
     mov     rcx,offset szRAX
     call    printf
     endif

     ret

main endp

end
</code>```

Building and running shows this output

```<code>C:\masm32>ml64.exe rax.asm /link /subsystem:console /defaultlib:kernel32.lib /defaultlib:user32.lib /defaultlib:libcmt.lib
Microsoft (R) Macro Assembler (x64) Version 14.29.30146.0
Copyright (C) Microsoft Corporation.  All rights reserved.

 Assembling: rax.asm
Microsoft (R) Incremental Linker Version 14.29.30146.0
Copyright (C) Microsoft Corporation.  All rights reserved.

/OUT:rax.exe
rax.obj
/subsystem:console
/defaultlib:kernel32.lib
/defaultlib:user32.lib
/defaultlib:libcmt.lib

C:\masm32>rax.exe
Symbol RAX exists
Symbol RAX exists
</code>```

Why does MASM output the same string twice?

Body:
Recently was working on a project to include 64-bit code when assembled under ML64.exe. However, this code actually included the 32-bit MASM directives, so the build failed.

IFNDEF RAX

.686P
.MODEL FLAT,STDCALL
OPTION CASEMAP:NONE
OPTION PROLOGUE:W32Prologue

ELSE

OPTION CASEMAP:NONE
OPTION PROLOGUE:W64Prologue
OPTION EPILOGUE:NONE

ENDIF

The fix was to change IFNDEF RAX to IFDEF RAX as follows

IFDEF RAX

OPTION CASEMAP:NONE
OPTION PROLOGUE:W64Prologue
OPTION EPILOGUE:NONE

ELSE

.686P
.MODEL FLAT,STDCALL
OPTION CASEMAP:NONE
OPTION PROLOGUE:W32Prologue

ENDIF

Wrote a simple example to show why using IFNDEF RAX is misleading

rax.asm

option casemap:none

extrn printf:proc

.data

     szRAX db 'Symbol RAX exists',0ah,0

.code

main proc

     ifdef   RAX
     mov     rcx,offset szRAX
     call    printf
     endif

     ifndef  RAX
     mov     rcx,offset szRAX
     call    printf
     endif

     ret

main endp

end

Building and running shows this output

C:\masm32>ml64.exe rax.asm /link /subsystem:console /defaultlib:kernel32.lib /defaultlib:user32.lib /defaultlib:libcmt.lib
Microsoft (R) Macro Assembler (x64) Version 14.29.30146.0
Copyright (C) Microsoft Corporation.  All rights reserved.

 Assembling: rax.asm
Microsoft (R) Incremental Linker Version 14.29.30146.0
Copyright (C) Microsoft Corporation.  All rights reserved.

/OUT:rax.exe
rax.obj
/subsystem:console
/defaultlib:kernel32.lib
/defaultlib:user32.lib
/defaultlib:libcmt.lib

C:\masm32>rax.exe
Symbol RAX exists
Symbol RAX exists

Why does MASM output the same string twice?


问:
Error installing Ansible Collection from Requirements file
I'm trying to install the cyberark.pas collection using a requirements file in my project.  Today I install the collection from AWX via ansible Galaxy, but the job fails a couple of times a day with the following error:

```<code>"stderr": "ERROR! Unexpected Exception, this is probably a bug: The read operation timed out",
</code>```

Here is my requirements file:

```<code>---
collections:
  - name: cyberark.pas
    source: https://galaxy.ansible.com
</code>```

After reading this ansible-galaxy timeout issue  https://github.com/ansible/galaxy/issues/2302 I thought I would change getting the collection from Github.  I found the collection here: https://github.com/cyberark/ansible-security-automation-collection and changed my requirements file to look like this:

```<code>---
collections:
  - name: https://github.com/cyberark/ansible-security-automation-collection.git
    type: git
</code>```

When I run this from AWX I get the error that it is expecting a .tar file and this is not a .tar file.

I was hoping someone might be able to help me with what I'm doing wrong.

Body:
I'm trying to install the cyberark.pas collection using a requirements file in my project.  Today I install the collection from AWX via ansible Galaxy, but the job fails a couple of times a day with the following error:

"stderr": "ERROR! Unexpected Exception, this is probably a bug: The read operation timed out",

Here is my requirements file:

---
collections:
  - name: cyberark.pas
    source: https://galaxy.ansible.com

After reading this ansible-galaxy timeout issue  https://github.com/ansible/galaxy/issues/2302 I thought I would change getting the collection from Github.  I found the collection here: https://github.com/cyberark/ansible-security-automation-collection and changed my requirements file to look like this:

---
collections:
  - name: https://github.com/cyberark/ansible-security-automation-collection.git
    type: git

When I run this from AWX I get the error that it is expecting a .tar file and this is not a .tar file.

I was hoping someone might be able to help me with what I'm doing wrong.


问:
"UseInMemoryDatabase", but app still uses my main DB
I am trying to set up my project to run integration tests for api.
In my test project I "rewrite" services to use InMemoryDatabase like this:

```<code>public class IntegrationTest
{
    protected readonly HttpClient TestClient;

    protected IntegrationTest()
    {
        var applicationFactory = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
        {
            builder.ConfigureServices(services =>
            {
                services.RemoveAll(typeof(DataContext));
                services.AddDbContext<DataContext>(options =>
                {
                    options.UseInMemoryDatabase("Test Db");
                });
            });
        });

        TestClient = applicationFactory.CreateClient();
    }

    protected async Task AuthenticateAsync()
    {
        TestClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", await GetJwtAsync());
    }

    protected async Task<Category> CreateCategoryAsync(Category category)
    {
        var response = await TestClient.PostAsJsonAsync("api/Categories", category);
        return await response.Content.ReadAsAsync<Category>();
    }
    private async Task<string> GetJwtAsync()
    {
        var response = await TestClient.PostAsJsonAsync("api/Categories", new CategoryDTO { CategoryName = "Test category" });
        var postResponse = await response.Content.ReadAsAsync<CategoryDTO>();
        return postResponse.CategoryName;
    }
}
</code>```

Test for example:

```<code>[Fact]
    public async Task Get_ReturnCategory()
    {
        //Arrange
        await AuthenticateAsync();
        var createdCategory = await CreateCategoryAsync(new Category { CategoryName = "Intest category"});

        //Act
        var response = await TestClient.GetAsync($"api/Categories/{createdCategory.Id.ToString()}");

        //Assert
        response.StatusCode.Should().Be(System.Net.HttpStatusCode.OK);
        var returnedCategory = await response.Content.ReadAsAsync<Category>();
        returnedCategory.Should().Be(createdCategory.Id);
        returnedCategory.CategoryName.Should().Be("Intest category");
    }
</code>```

Why new instances are still appearing in my main mssql db? How I fix this?

Body:
I am trying to set up my project to run integration tests for api.
In my test project I "rewrite" services to use InMemoryDatabase like this:

public class IntegrationTest
{
    protected readonly HttpClient TestClient;

    protected IntegrationTest()
    {
        var applicationFactory = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
        {
            builder.ConfigureServices(services =>
            {
                services.RemoveAll(typeof(DataContext));
                services.AddDbContext<DataContext>(options =>
                {
                    options.UseInMemoryDatabase("Test Db");
                });
            });
        });

        TestClient = applicationFactory.CreateClient();
    }

    protected async Task AuthenticateAsync()
    {
        TestClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", await GetJwtAsync());
    }

    protected async Task<Category> CreateCategoryAsync(Category category)
    {
        var response = await TestClient.PostAsJsonAsync("api/Categories", category);
        return await response.Content.ReadAsAsync<Category>();
    }
    private async Task<string> GetJwtAsync()
    {
        var response = await TestClient.PostAsJsonAsync("api/Categories", new CategoryDTO { CategoryName = "Test category" });
        var postResponse = await response.Content.ReadAsAsync<CategoryDTO>();
        return postResponse.CategoryName;
    }
}

Test for example:

[Fact]
    public async Task Get_ReturnCategory()
    {
        //Arrange
        await AuthenticateAsync();
        var createdCategory = await CreateCategoryAsync(new Category { CategoryName = "Intest category"});

        //Act
        var response = await TestClient.GetAsync($"api/Categories/{createdCategory.Id.ToString()}");

        //Assert
        response.StatusCode.Should().Be(System.Net.HttpStatusCode.OK);
        var returnedCategory = await response.Content.ReadAsAsync<Category>();
        returnedCategory.Should().Be(createdCategory.Id);
        returnedCategory.CategoryName.Should().Be("Intest category");
    }

Why new instances are still appearing in my main mssql db? How I fix this?


问:
Create and start a container from anohter container windows docker
I have a service which has to spawn other service instances. As we need to dockerize this, I created images for both services lets say service1 and service2.

Both images are Window images.

I have started container1 of service1. Now container1 has to start and create new containers of service2.
Is there any way to do it in windows for windows containers?

I found few articles relating to start linux containers from other linux container using docker.sock. But information regarding same for windows container is missing.


问:
How can I run an asynchronous function in a Custom Link? (resolve race condition with refresh token of third-party provider)
I'm having a very specific problem in which I use a third-party authentication provider (Clerk) that invalidates and refreshes their token in the browser very frequently (1-2 minutes).  But Clerk is only able to run js and refresh the token if my page has focus. So what happens, very frequently, is that a user change focus to another tab or software, then when they return to my page a race condition occurs, where Clerk begins to refresh the token but, simultaneously, tRPC is already making a request to my server.  So, by the time this first tRPC's request arrives at my server, Clerk hasn't had the time to refresh it yet, and users get an unauthorized error.

This is not a major problem right now because of automatic retries, but I'm trying to solve it anyway.

My logic was to add a Custom Link to tRPC, requesting the Clerk authed user and awaiting for it to refresh (if needed) before returning, but apparently I can't run asynchronous functions inside its body.

I also realized that maybe my question can go deeper in: should token refresh be eager (but only if needed) or lazy?

Could someone shine a light on how to resolve this, please?


问:
Type Mismatch Error (13) on Split function call
I am working on a project that extracts the URLs of 9 images. If one is not available, it is represented by the "missing-image" URL. I need to cycle through the list and process any that are not "missing". I used the TextJoin function to build the list (some originating columns are non-contiguous), with the pipe ("|") symbol as the delimiter.

```<code>    Dim VarSKU, MissingImage, Images(), HandleCol As String
    ...
        Images = Split(ActiveCell.Value, "|")

</code>```

I omitted the code between the two statements. None of it makes any reference whatsoever to Images.

I confirmed that the active cell is the one I need to process. Its value is: http://www.image.src/url_image/0050IG-RN-2160-PH0.jpg|http://www.image.src/url_image/missing-image.jpg|http://www.image.src/url_image/missing-image.jpg|http://www.image.src/url_image/missing-image.jpg|http://www.image.src/url_image/missing-image.jpg|http://www.image.src/url_image/missing-image.jpg|http://www.image.src/url_image/missing-image.jpg|http://www.image.src/url_image/missing-image.jpg|http://www.image.src/url_image/missing-image.jpg

I cannot see why the error is being thrown. I checked the VarTypes of both arguments - they are both String. Images was declared as a String Array.

I must be missing something obvious. Please help.

Body:
I am working on a project that extracts the URLs of 9 images. If one is not available, it is represented by the "missing-image" URL. I need to cycle through the list and process any that are not "missing". I used the TextJoin function to build the list (some originating columns are non-contiguous), with the pipe ("|") symbol as the delimiter.

    Dim VarSKU, MissingImage, Images(), HandleCol As String
    ...
        Images = Split(ActiveCell.Value, "|")

I omitted the code between the two statements. None of it makes any reference whatsoever to Images.

I confirmed that the active cell is the one I need to process. Its value is: http://www.image.src/url_image/0050IG-RN-2160-PH0.jpg|http://www.image.src/url_image/missing-image.jpg|http://www.image.src/url_image/missing-image.jpg|http://www.image.src/url_image/missing-image.jpg|http://www.image.src/url_image/missing-image.jpg|http://www.image.src/url_image/missing-image.jpg|http://www.image.src/url_image/missing-image.jpg|http://www.image.src/url_image/missing-image.jpg|http://www.image.src/url_image/missing-image.jpg

I cannot see why the error is being thrown. I checked the VarTypes of both arguments - they are both String. Images was declared as a String Array.

I must be missing something obvious. Please help.


问:
How to auto hide appbar flutter
Can anyone tell how to implementation auto hide appbar when scroll down and if we scroll up the app bar appear again.
Any code example will be appreciated

New to flutter curious about how to implement this

Title: How to auto hide appbar flutter


问:
Why isn't Visual Studio Code python debugger finding my modules?
I am trying to import a module of a parallel folder in my python project. The structure is as follows:

```<code>~/src/
  |
  |---calculator/
        |
        |---calculator.py
        |---__init__.py

  |---main/
        |---__main__.py
</code>```

I specifically want to import calculator.py on my __main__.py module. I also wrote this lines on my main module to help me import parallel modules:

```<code>import sys
sys.path.append("../")
from calculator import calculator.py
</code>```

When simply running the module by python main.py everything works fine, but when trying to debug, i get a "No module named calculator" error.

I've tried to uninstall the python extension and change its version, i tried uninstalling and installing back vscode, i tried to modify the launch.json adding the env variable:

```<code>"version": "0.2.0",
    "configurations": [
        {
            "name": "Python: modulo",
            "type": "python",
            "request": "launch",
            "module": "Main",
            "justMyCode": true,
            "env": { "PYTHONPATH": "${workspaceFolder}/src:${env:PYTHONPATH}"},
        }
    ]
</code>```

i also tried "PYTHONPATH": "${workspaceFolder}${pathSeparator}${env:PYTHONPATH}"
Then i put this line i found from another answer on my User.settings.json

```<code>"terminal.integrated.env.windows": {
        "PYTHONPATH": "${workspaceFolder}"
    }
</code>```

but nothing worked.

Body:
I am trying to import a module of a parallel folder in my python project. The structure is as follows:

~/src/
  |
  |---calculator/
        |
        |---calculator.py
        |---__init__.py

  |---main/
        |---__main__.py

I specifically want to import calculator.py on my __main__.py module. I also wrote this lines on my main module to help me import parallel modules:

import sys
sys.path.append("../")
from calculator import calculator.py

When simply running the module by python main.py everything works fine, but when trying to debug, i get a "No module named calculator" error.

I've tried to uninstall the python extension and change its version, i tried uninstalling and installing back vscode, i tried to modify the launch.json adding the env variable:

"version": "0.2.0",
    "configurations": [
        {
            "name": "Python: modulo",
            "type": "python",
            "request": "launch",
            "module": "Main",
            "justMyCode": true,
            "env": { "PYTHONPATH": "${workspaceFolder}/src:${env:PYTHONPATH}"},
        }
    ]

i also tried "PYTHONPATH": "${workspaceFolder}${pathSeparator}${env:PYTHONPATH}"
Then i put this line i found from another answer on my User.settings.json

"terminal.integrated.env.windows": {
        "PYTHONPATH": "${workspaceFolder}"
    }

but nothing worked.


问:
VB.NET XAML : Why the ShowDialog() function call twice the child window?
My sub code is very short :

```<code>Private Sub B_FicheRecette_Click(sender As Object, e As RoutedEventArgs) Handles B_FicheRecette.Click

     Dim Fen As New ClsFenFicheRecette

     Fen.ShowDialog()

End Sub
</code>```

B_FicheRecette_Click is a button.

The first call to Fen work well.

On the child widow (Fen), there is a button with the Close() function.

When application is back to B_FicheRecette_Click sub, it  execute ShowDialog() a second time for unknown reason.

I'm experimented with VB from 80's, but with this issue, my mind is blind.

Body:
My sub code is very short :

Private Sub B_FicheRecette_Click(sender As Object, e As RoutedEventArgs) Handles B_FicheRecette.Click

     Dim Fen As New ClsFenFicheRecette

     Fen.ShowDialog()

End Sub

B_FicheRecette_Click is a button.

The first call to Fen work well.

On the child widow (Fen), there is a button with the Close() function.

When application is back to B_FicheRecette_Click sub, it  execute ShowDialog() a second time for unknown reason.

I'm experimented with VB from 80's, but with this issue, my mind is blind.


问:
Google Sheets: Right vertical axis gridlines not working
In Google Sheets, when creating a chart using both vertical axes, I can somehow turn on and off the gridlines for the (left) vertical axis but not for the right vertical axis.

In the first image, I'm showing the Major Gridlines option selected. If unselected, as expected, the gridlines turn off.

The second image shows the same option selected for the right vertical axis, but no gridlines are shown.

A curious fact I've been experiencing with Google Sheets (and maybe other Google's products), is that whenever I look up for "unusual customization" on Google's search engine, I only get the most basic results and, more often than not, they have nothing to do with what I was looking for. As an example, searching for "sheets right vertical axis gridline not showing" returns nothing relevant. Has anybody else noticed this?

Thanks

What I've tried: I've tried changing the color, with no effects.