问:
Partial calldata using ethers
I'd like to serialize a call using ethers, but only partially.

```<code>contract MockCall {
    struct VoteResults {
        uint256 votes;
        bytes data;
    }

    event LogParam(uint256 param);
    event LogParam(string name);
    event LogParam(VoteResults[] results);

    bool public isAction1 = false;
    bool public isAction2 = false;

    //I've only created this method so type chain would generate method stub
    function Action(uint256 param1, string calldata name) public {
        isAction1 = true;
    }

    // Intentionally leave 2 calldata parameters to verify appending calldata can work with trailing dynamic parameter
    function Action(uint256 param1, string calldata name, VoteResults[] calldata voteResults) public {
        isAction2 = true;
        emit LogParam(param1);
        emit LogParam(name);
        emit LogParam(voteResults);
    }
}
</code>```

I would like to partially build the calldata, and my contract is going to handle injecting the rest of the parameters.

I've tried a few ways:

This way throws an error, in hexify, and sometimes json

```<code>let encodedFunctionCall = '';
try {
  const rawInterface = new Interface("Action(uint256,string,(uint256,bytes)[]");
  encodedFunctionCall = rawInterface.encodeFunctionData("Action(uint256,string,(uint256,bytes)[]", [BigNumber.from(5), "Abra"]);
}
catch(err) {
  console.log(err);
}
</code>```

This doesn't compile since it expects 3 parameters

```<code>const encodedFunctionCall = mockCall.interface.encodeFunctionData("Action(uint256,string,(uint256,bytes)[])", [BigNumber.from(5), "Abra"])
</code>```

How do I partially construct calldata?

Title: Partial calldata using ethers

Body:
I'd like to serialize a call using ethers, but only partially.

contract MockCall {
    struct VoteResults {
        uint256 votes;
        bytes data;
    }

    event LogParam(uint256 param);
    event LogParam(string name);
    event LogParam(VoteResults[] results);

    bool public isAction1 = false;
    bool public isAction2 = false;

    //I've only created this method so type chain would generate method stub
    function Action(uint256 param1, string calldata name) public {
        isAction1 = true;
    }

    // Intentionally leave 2 calldata parameters to verify appending calldata can work with trailing dynamic parameter
    function Action(uint256 param1, string calldata name, VoteResults[] calldata voteResults) public {
        isAction2 = true;
        emit LogParam(param1);
        emit LogParam(name);
        emit LogParam(voteResults);
    }
}

I would like to partially build the calldata, and my contract is going to handle injecting the rest of the parameters.

I've tried a few ways:

This way throws an error, in hexify, and sometimes json

let encodedFunctionCall = '';
try {
  const rawInterface = new Interface("Action(uint256,string,(uint256,bytes)[]");
  encodedFunctionCall = rawInterface.encodeFunctionData("Action(uint256,string,(uint256,bytes)[]", [BigNumber.from(5), "Abra"]);
}
catch(err) {
  console.log(err);
}

This doesn't compile since it expects 3 parameters

const encodedFunctionCall = mockCall.interface.encodeFunctionData("Action(uint256,string,(uint256,bytes)[])", [BigNumber.from(5), "Abra"])

How do I partially construct calldata?


来源: stackexchange

问:
How to fix "Attempting to unpack a non-sequence"
I have a server as follows:

```<code>import string
import zmq

host = '127.0.0.1'
port = 6789
ctx = zmq.Context()
pub = ctx.socket(zmq.PUB)
pub.bind('tcp://%s:%s' % (host, port))

with open('mammoth.txt', 'rt') as poem:
    words = poem.read()
for word in words.split():
    word = word.strip(string.punctuation)
    data = word.encode('utf-8')
    if word.startswith(('a','e','o','u','A','e','i','o','u')):
        pub.send_multipart([b'vowels', data])
if len(word) == 5:
    pub.send_multipart([b'five', data])
</code>```

and a client:

```<code>import string
import zmq

host = '127.0.0.1'
port = 6789

ctx = zmq.Context()
sub = ctx.socket(zmq.SUB)
sub.connect('tcp://%s:%s' % (host, port))
sub.setsockopt(zmq.SUBSCRIBE, b'vowels')
sub.setsockopt(zmq.SUBSCRIBE, b'five')
while True:
    topic, word = sub.recv_multipart()
    print(topic, word)
</code>```

Specifically, the:

```<code>topic, word = sub.recv_multipart()
</code>```

is giving me an unpacking sequence issue.

I am a little bit out of practice, and not sure how to get around this.

ContentLicense: CC BY-SA 4.0

Body:
I have a server as follows:

import string
import zmq

host = '127.0.0.1'
port = 6789
ctx = zmq.Context()
pub = ctx.socket(zmq.PUB)
pub.bind('tcp://%s:%s' % (host, port))

with open('mammoth.txt', 'rt') as poem:
    words = poem.read()
for word in words.split():
    word = word.strip(string.punctuation)
    data = word.encode('utf-8')
    if word.startswith(('a','e','o','u','A','e','i','o','u')):
        pub.send_multipart([b'vowels', data])
if len(word) == 5:
    pub.send_multipart([b'five', data])

and a client:

import string
import zmq

host = '127.0.0.1'
port = 6789

ctx = zmq.Context()
sub = ctx.socket(zmq.SUB)
sub.connect('tcp://%s:%s' % (host, port))
sub.setsockopt(zmq.SUBSCRIBE, b'vowels')
sub.setsockopt(zmq.SUBSCRIBE, b'five')
while True:
    topic, word = sub.recv_multipart()
    print(topic, word)

Specifically, the:

topic, word = sub.recv_multipart()

is giving me an unpacking sequence issue.

I am a little bit out of practice, and not sure how to get around this.


问:
Can't access build directory - symfony webpack encore
I have installed webpack-encore-bundle with npm on my Symfony 6.1 skeleton project and in the web browser I can't access to files in build directory (404 - route not found).

NPM successfully compiles the assets.

I'm learning to work with Docker (image php:apache-bullseye).

```<code>// app/webpack.config.js

const Encore = require('@symfony/webpack-encore');

if (!Encore.isRuntimeEnvironmentConfigured()) {
    Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}

Encore
    // directory where compiled assets will be stored
    .setOutputPath('public/build/')
    // public path used by the web server to access the output path
    .setPublicPath('/build')

    .addEntry('app', './assets/app.js')

    .enableStimulusBridge('./assets/controllers.json')

    .splitEntryChunks()

    .enableSingleRuntimeChunk()

    .cleanupOutputBeforeBuild()
    .enableBuildNotifications()
    .enableSourceMaps(!Encore.isProduction())

    .enableVersioning(Encore.isProduction())

    .configureBabelPresetEnv((config) => {
        config.useBuiltIns = 'usage';
        config.corejs = '3.23';
    })

    .enableLessLoader()
;

module.exports = Encore.getWebpackConfig();
</code>```

I have tried to install apache-pack (.htaccess), security-bundle, change web/encore settings and within 2 days I've not found solution.

Body:
I have installed webpack-encore-bundle with npm on my Symfony 6.1 skeleton project and in the web browser I can't access to files in build directory (404 - route not found).

NPM successfully compiles the assets.

I'm learning to work with Docker (image php:apache-bullseye).

// app/webpack.config.js

const Encore = require('@symfony/webpack-encore');

if (!Encore.isRuntimeEnvironmentConfigured()) {
    Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}

Encore
    // directory where compiled assets will be stored
    .setOutputPath('public/build/')
    // public path used by the web server to access the output path
    .setPublicPath('/build')

    .addEntry('app', './assets/app.js')

    .enableStimulusBridge('./assets/controllers.json')

    .splitEntryChunks()

    .enableSingleRuntimeChunk()

    .cleanupOutputBeforeBuild()
    .enableBuildNotifications()
    .enableSourceMaps(!Encore.isProduction())

    .enableVersioning(Encore.isProduction())

    .configureBabelPresetEnv((config) => {
        config.useBuiltIns = 'usage';
        config.corejs = '3.23';
    })

    .enableLessLoader()
;

module.exports = Encore.getWebpackConfig();

I have tried to install apache-pack (.htaccess), security-bundle, change web/encore settings and within 2 days I've not found solution.


问:
window.innerWidth When I run this, the action is not performed
I am making a menu bar but window.innerWidth does not execute the action of collapsing the bar without covering the dashboard, that is, the dashboard is covered by the bar.
I try to collapse the bar together with the dashboard, but the bar covers the dashboard.
https://github.com/Opalo2289/sidenav.git

```<code>
import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { navbarData } from './nav-data';

interface SideNavToggle {
  screenWidth: number;
  collapsed: boolean;
}

@Component({
  selector: 'app-sidenav',
  templateUrl: './sidenav.component.html',
  styleUrls: ['./sidenav.component.scss']
})
export class SidenavComponent implements OnInit {

  @Output() onToggleSidenav: EventEmitter<SideNavToggle> = new EventEmitter();
  collapsed = false;
  screenWidth = 0;
  navData = navbarData;

  constructor() { }

  ngOnInit(): void {
    this.screenWidth = window.innerWidth;
  }

  toggleCollapse(): void {
    this.collapsed = !this.collapsed;
    this.onToggleSidenav.emit({collapsed: this.collapsed, screenWidth: this.screenWidth})
  }

  closeSidenav(): void {
    this.collapsed = false;
    this.onToggleSidenav.emit({collapsed: this.collapsed, screenWidth: this.screenWidth})
  }

}
</code>```

Body:
I am making a menu bar but window.innerWidth does not execute the action of collapsing the bar without covering the dashboard, that is, the dashboard is covered by the bar.
I try to collapse the bar together with the dashboard, but the bar covers the dashboard.
https://github.com/Opalo2289/sidenav.git

import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { navbarData } from './nav-data';

interface SideNavToggle {
  screenWidth: number;
  collapsed: boolean;
}

@Component({
  selector: 'app-sidenav',
  templateUrl: './sidenav.component.html',
  styleUrls: ['./sidenav.component.scss']
})
export class SidenavComponent implements OnInit {

  @Output() onToggleSidenav: EventEmitter<SideNavToggle> = new EventEmitter();
  collapsed = false;
  screenWidth = 0;
  navData = navbarData;

  constructor() { }

  ngOnInit(): void {
    this.screenWidth = window.innerWidth;
  }

  toggleCollapse(): void {
    this.collapsed = !this.collapsed;
    this.onToggleSidenav.emit({collapsed: this.collapsed, screenWidth: this.screenWidth})
  }

  closeSidenav(): void {
    this.collapsed = false;
    this.onToggleSidenav.emit({collapsed: this.collapsed, screenWidth: this.screenWidth})
  }

}


问:
ngx formly formArray without formcontrol
I have a requirement to create a typeahead component inside a form and storing the results of the search in an array. I am new to angular formly and am trying to achieve the ask using a formArray. I have tried using an empty formArray and pushing the selected value to it but it doesn't get reflected in the model or  form value.Please help.

I have tried using an empty formArray and pushing the selected value to it but it doesn't get reflected in the model or  form value.


问:
false 'error: package * does not exist' in Android Studio
I've got a bunch of errors in AS which basically tell me that there is no file and / or it wasn't able to read it. The problem is, all the files it's looking for are there. This must be and AS related issue. Some examples:

Error 1:

```<code>error: package com.blazecode.scrapguidev2.ui.Items.enums does not exist
import com.blazecode.scrapguidev2.ui.Items.enums.Modpack;
                                                ^
</code>```

As you can see the file is right there.

Error 2:

```<code>error: package com.blazecode.scrapguidev2.ui.Items.util does not exist
import com.blazecode.scrapguidev2.ui.Items.util.ModpackTypeConverter;
                                               ^
</code>```

Same story here

Things I've tried:

Clean build

Rebuild project

Invalidate cache and restart (ticked both boxes)

Delete .idea

Delete build

Delete app/build

Restart computer

Versions:

Kotlin: 1.7.10

Gradle: 7.3.1

AndroidStudio: Dolphin | 2021.3.1 Patch 1 Build #AI-213.7172.25.2113.9123335

How could this be fixed?

Body:
I've got a bunch of errors in AS which basically tell me that there is no file and / or it wasn't able to read it. The problem is, all the files it's looking for are there. This must be and AS related issue. Some examples:

Error 1:

error: package com.blazecode.scrapguidev2.ui.Items.enums does not exist
import com.blazecode.scrapguidev2.ui.Items.enums.Modpack;
                                                ^

As you can see the file is right there.

Error 2:

error: package com.blazecode.scrapguidev2.ui.Items.util does not exist
import com.blazecode.scrapguidev2.ui.Items.util.ModpackTypeConverter;
                                               ^

Same story here

Things I've tried:

Clean build

Rebuild project

Invalidate cache and restart (ticked both boxes)

Delete .idea

Delete build

Delete app/build

Restart computer

Versions:

Kotlin: 1.7.10

Gradle: 7.3.1

AndroidStudio: Dolphin | 2021.3.1 Patch 1 Build #AI-213.7172.25.2113.9123335

How could this be fixed?


问:
LocateCenterOnScreen with Mutliple Images
I have tried to use multiple PNG files inside a folder to locate on a screen. My script scrolls down inside of Google searches, and at the same time it looks for the .png files. My problem is if I search them one by one all works well
but if I search it from a folder where all are inside   I get error here are two codes that I use, both get error: Failed to read x.png because file is missing, has improper permissions, or is an unsupported or invalid format

I checked the Folder path and Folder and Images, all is fine. I also make New Folders to put Files inside, but it happens also. To try if permission problem I use single locate for the images and all works it pyautogui found the images.

Used code 1:

```<code>def locateAndClickSymbolNeonVar():
  image_list = []
# Get list of all files in current directory

  directory = os.listdir(r'scr\image\NeonandSerp')

# Find files that end with .png or .jpg and add to image_list
    for file in directory:
        if file.endswith('.png') or file.endswith('.jpg'):
            image_list.append(file)

# Loop through list to find all the images
    for image in image_list:
# Locate on screen the current image
        time.sleep(2)
        coordinates = pyautogui.locateCenterOnScreen(image)
# if locateOnScreen is not returning None
# (locateOnScreen will return none if nothing is found on the screen)
        if coordinates is not None:
            print("found neon")
            click(coordinates)
            CheckLinkClickFailedTrueAndCurl()
        else:
            print("not found neon")
            CheckLinkClickFailedTrueAndCurl()
</code>```

used code 2:

```<code>def locateAndClickSymbolNeonVar():
    ## folder directory of where the .png files are
    directory = r'scr\image\NeonandSerp'
    ## iterate through every .png images in a folder (Neon.png, Neon1.png, Neon2.png ect.)
    #for images in os.listdir(directory):
        if images.endswith(".png"):
            # Locate on screen the current image
            time.sleep(2)
            coordinates = pyautogui.locateCenterOnScreen(images)
            # if locateOnScreen is not returning None
            # (locateOnScreen will return none if nothing is found on the screen)
        if coordinates is not None:
            print("found neon")
            click(coordinates)
            CheckLinkClickFailedTrueAndCurl()
        else:
            print("not found neon")
            CheckLinkClickFailedTrueAndCurl()
</code>```

and please sorry for my bad English, I hope I have explained it well

Body:
I have tried to use multiple PNG files inside a folder to locate on a screen. My script scrolls down inside of Google searches, and at the same time it looks for the .png files. My problem is if I search them one by one all works well
but if I search it from a folder where all are inside   I get error here are two codes that I use, both get error: Failed to read x.png because file is missing, has improper permissions, or is an unsupported or invalid format

I checked the Folder path and Folder and Images, all is fine. I also make New Folders to put Files inside, but it happens also. To try if permission problem I use single locate for the images and all works it pyautogui found the images.

Used code 1:

def locateAndClickSymbolNeonVar():
  image_list = []
# Get list of all files in current directory

  directory = os.listdir(r'scr\image\NeonandSerp')

# Find files that end with .png or .jpg and add to image_list
    for file in directory:
        if file.endswith('.png') or file.endswith('.jpg'):
            image_list.append(file)

# Loop through list to find all the images
    for image in image_list:
# Locate on screen the current image
        time.sleep(2)
        coordinates = pyautogui.locateCenterOnScreen(image)
# if locateOnScreen is not returning None
# (locateOnScreen will return none if nothing is found on the screen)
        if coordinates is not None:
            print("found neon")
            click(coordinates)
            CheckLinkClickFailedTrueAndCurl()
        else:
            print("not found neon")
            CheckLinkClickFailedTrueAndCurl()

used code 2:

def locateAndClickSymbolNeonVar():
    ## folder directory of where the .png files are
    directory = r'scr\image\NeonandSerp'
    ## iterate through every .png images in a folder (Neon.png, Neon1.png, Neon2.png ect.)
    #for images in os.listdir(directory):
        if images.endswith(".png"):
            # Locate on screen the current image
            time.sleep(2)
            coordinates = pyautogui.locateCenterOnScreen(images)
            # if locateOnScreen is not returning None
            # (locateOnScreen will return none if nothing is found on the screen)
        if coordinates is not None:
            print("found neon")
            click(coordinates)
            CheckLinkClickFailedTrueAndCurl()
        else:
            print("not found neon")
            CheckLinkClickFailedTrueAndCurl()

and please sorry for my bad English, I hope I have explained it well


问:
CoreData NSPredicate: fetch object with UUID that is contained within a Set<UUID>
I have a CoreData entity with an identifier of type UUID, declared as: @NSManaged public var uuid: UUID? .

I want to create a fetch request that would return all entities for which the identifier (uuid) is contained within a Set (or array) of UUIDs. Here's my function so far:

```<code>    func delete(_ identifiers: Set<UUID>) {
        let idsToFetch = positionIDs.map { $0 as NSUUID }
        // idsToFetch is of type Array<NSUUID>

        let fetchRequest = MyEntity.fetchRequest()
        fetchRequest.predicate = NSPredicate(format: "%K IN %@", #keyPath(MyEntity.uuid), idsToFetch)

        do {
            let result = try mainContext.fetch(fetchRequest)

            for object in result {
                mainContext.delete(object)
            }
        } catch {
            // error management out of scope of this question
            return
        }
    }
</code>```

I saw other answers and this post that suggest to cast each element to CArgVar, but this post suggests to use Foundation bridging equivalent instead. Either way don't return any result.

I made sure the elements I'm fetching do exist, by opening the .sql file in an editor. I can confirm that the UUID is written, but shows up as blob.

Thank you for any insight

Body:
I have a CoreData entity with an identifier of type UUID, declared as: @NSManaged public var uuid: UUID? .

I want to create a fetch request that would return all entities for which the identifier (uuid) is contained within a Set (or array) of UUIDs. Here's my function so far:

    func delete(_ identifiers: Set<UUID>) {
        let idsToFetch = positionIDs.map { $0 as NSUUID }
        // idsToFetch is of type Array<NSUUID>

        let fetchRequest = MyEntity.fetchRequest()
        fetchRequest.predicate = NSPredicate(format: "%K IN %@", #keyPath(MyEntity.uuid), idsToFetch)

        do {
            let result = try mainContext.fetch(fetchRequest)

            for object in result {
                mainContext.delete(object)
            }
        } catch {
            // error management out of scope of this question
            return
        }
    }

I saw other answers and this post that suggest to cast each element to CArgVar, but this post suggests to use Foundation bridging equivalent instead. Either way don't return any result.

I made sure the elements I'm fetching do exist, by opening the .sql file in an editor. I can confirm that the UUID is written, but shows up as blob.

Thank you for any insight


问:
gRPC python socket_mutator
I am trying to make a gRPC client to use a specific exit interface.

For that, I am setting the value for the "socket_mutator" in the channel_arguments.
I defined a function that takes a socket as an argument and modifies it however I receive a:
TypeError: Expected int, bytes, or behavior, got <class 'function'>

Does someone know what should I place in the socket_mutator value instead?

Thank you for your time.

Title: gRPC python socket_mutator


问:
Delaying mock response for 5 seconds with GuzzleHttp - MockHandler
I have the following PHP / PHPUnit code:

```<code><?php

namespace Experiments\Tests;

use GuzzleHttp\Client as HttpClient;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\RequestOptions;
use PHPUnit\Framework\TestCase;

final class ApiGatewayTest extends TestCase
{

    public function testExecute()
    {

        $req = json_decode('{ "root": { "param1": [ "value1" ] } }', true);
        $resp = '{ "echo": { "root": { "param1": [ "value1" ] } } }';

        $options = [
            RequestOptions::HEADERS => [
                'Content-Type' => 'application/json',
            ],
            RequestOptions::JSON =>  $req,
            RequestOptions::TIMEOUT => 10,
        ];

        $handlerStack = HandlerStack::create(
            new MockHandler([new Response(200, ['Content-Type' => 'application/json'], $resp)])
        );

        $client = new HttpClient(['handler' => $handlerStack]);

        $response = $client->request(
            'POST',
            'whatever-just-mocking',
            $options
        );

        $responseBodyJson = (string) $response->getBody();
        $responseBody = json_decode($responseBodyJson, true);

        $this->assertSame('value1', $responseBody['echo']['root']['param1'][0]);
    }
}
</code>```

The unit test above works just fine. You can test it with:

```<code>$ ./vendor/bin/phpunit --filter 'testExecute\b'
</code>```

What I need: Delay the mock response for 5 seconds, so I can implement and test a timeout handling in the same class above.

Any idea on how to do that?

Thanks!

Body:
I have the following PHP / PHPUnit code:

<?php

namespace Experiments\Tests;

use GuzzleHttp\Client as HttpClient;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\RequestOptions;
use PHPUnit\Framework\TestCase;

final class ApiGatewayTest extends TestCase
{

    public function testExecute()
    {

        $req = json_decode('{ "root": { "param1": [ "value1" ] } }', true);
        $resp = '{ "echo": { "root": { "param1": [ "value1" ] } } }';

        $options = [
            RequestOptions::HEADERS => [
                'Content-Type' => 'application/json',
            ],
            RequestOptions::JSON =>  $req,
            RequestOptions::TIMEOUT => 10,
        ];

        $handlerStack = HandlerStack::create(
            new MockHandler([new Response(200, ['Content-Type' => 'application/json'], $resp)])
        );

        $client = new HttpClient(['handler' => $handlerStack]);

        $response = $client->request(
            'POST',
            'whatever-just-mocking',
            $options
        );

        $responseBodyJson = (string) $response->getBody();
        $responseBody = json_decode($responseBodyJson, true);

        $this->assertSame('value1', $responseBody['echo']['root']['param1'][0]);
    }
}

The unit test above works just fine. You can test it with:

$ ./vendor/bin/phpunit --filter 'testExecute\b'

What I need: Delay the mock response for 5 seconds, so I can implement and test a timeout handling in the same class above.

Any idea on how to do that?

Thanks!


问:
ffmpeg fails to broadcast rtmp telegram video
I am trying to transfer an mp4 file to Telegram RTMP live using the following command:

```<code>$cmd = "ffmpeg -i video.mp4 -c:v libx264 -c:a aac -b:v 2000k -f flv " . $url . $key . "";
exec($cmd, $output, $return);
</code>```

$url and $key values obtained using MadelineProto for the channel. No picture or sound appears.

Creating a broadcast in the channel and receiving rtmp data accordingly. Everything is clear here

```<code>$Updates = $MadelineProto->phone->createGroupCall(peer: $channel, title: $title);
$phone_GroupCallStreamRtmpUrl = $MadelineProto->phone->getGroupCallStreamRtmpUrl(peer: $channel, revoke: 1 );
$url = $phone_GroupCallStreamRtmpUrl['url'];
$key = $phone_GroupCallStreamRtmpUrl['key'];
</code>```

Perhaps something needs to be specified in the ffmpeg values. Tell me please

Body:
I am trying to transfer an mp4 file to Telegram RTMP live using the following command:

$cmd = "ffmpeg -i video.mp4 -c:v libx264 -c:a aac -b:v 2000k -f flv " . $url . $key . "";
exec($cmd, $output, $return);

$url and $key values obtained using MadelineProto for the channel. No picture or sound appears.

Creating a broadcast in the channel and receiving rtmp data accordingly. Everything is clear here

$Updates = $MadelineProto->phone->createGroupCall(peer: $channel, title: $title);
$phone_GroupCallStreamRtmpUrl = $MadelineProto->phone->getGroupCallStreamRtmpUrl(peer: $channel, revoke: 1 );
$url = $phone_GroupCallStreamRtmpUrl['url'];
$key = $phone_GroupCallStreamRtmpUrl['key'];

Perhaps something needs to be specified in the ffmpeg values. Tell me please


问:
A problem with making phyloseq object - Found more than one class "phylo" in cache
I`m trying to make a phyloseq object in R this is my script:

```<code>Phyloseqb<- qza_to_phyloseq(
metadata = "E:/pesticide 4 months work result/pesticide bacteria/pesticidebacteria/metadata1.txt",
features= "E:/pesticide 4 months work result/pesticide bacteria/pesticidebacteria/table_final_rarefied.qza",
tree="E:/pesticide 4 months work result/pesticide bacteria/pesticidebacteria/asvs-tree.qza",
taxonomy="E:/pesticide 4 months work result/pesticide bacteria/pesticidebacteria/classification.qza")
</code>```

But I`m getting an error :

```<code>Found more than one class "phylo" in cache; using the first, from namespace 'phyloseq'
Also defined by ‘tidytree’ ‘RNeXML’
Found more than one class "phylo" in cache; using the first, from namespace 'phyloseq'
Also defined by ‘tidytree’ ‘RNeXML’
Error in validObject(.Object) : invalid class “phyloseq” object:
 Component sample names do not match.
 Try sample_names()
</code>```

How can I solve it ?

I tried to create another Phyloseq object but I`m getting the same error

Body:
I`m trying to make a phyloseq object in R this is my script:

Phyloseqb<- qza_to_phyloseq(
metadata = "E:/pesticide 4 months work result/pesticide bacteria/pesticidebacteria/metadata1.txt",
features= "E:/pesticide 4 months work result/pesticide bacteria/pesticidebacteria/table_final_rarefied.qza",
tree="E:/pesticide 4 months work result/pesticide bacteria/pesticidebacteria/asvs-tree.qza",
taxonomy="E:/pesticide 4 months work result/pesticide bacteria/pesticidebacteria/classification.qza")

But I`m getting an error :

Found more than one class "phylo" in cache; using the first, from namespace 'phyloseq'
Also defined by ‘tidytree’ ‘RNeXML’
Found more than one class "phylo" in cache; using the first, from namespace 'phyloseq'
Also defined by ‘tidytree’ ‘RNeXML’
Error in validObject(.Object) : invalid class “phyloseq” object:
 Component sample names do not match.
 Try sample_names()

How can I solve it ?

I tried to create another Phyloseq object but I`m getting the same error


问:
Apache Pulsar Helm install failed on managed GKEAutopilot cluster
```<code>reconciliation failed: Helm install failed: services is forbidden: User "system:serviceaccount:flux-system:helm-controller" cannot create resource "services" in API group │
│  "" in the namespace "kube-system": GKEAutopilot authz: the namespace "kube-system" is managed and the request's verb "create" is denied                                                                           │
│   Warning  error  21s  helm-controller  reconciliation failed: Operation cannot be fulfilled on helmreleases.helm.toolkit.fluxcd.io "pulsar": the object has been modified; please apply your changes to the lates │
│ t version and try again
</code>```

Is there some option I could --set to avoid this?
Is there a component I have to disable to avoid this?

I'm trying to install pulsar via Helm and via flux.cd

My two sources are:

helmrepo.yaml

apiVersion: source.toolkit.fluxcd.io/v1beta2
kind: HelmRepository
metadata:
  name: pulsar
  namespace: pulsar
spec:
  interval: 1m0s
  url: https://pulsar.apache.org/charts

```
<p>helmrelease.yaml</p>
```apiVersion: helm.toolkit.fluxcd.io/v2beta1
kind: HelmRelease
metadata:
  name: pulsar
  namespace: pulsar
spec:
  chart:
    spec:
      chart: pulsar
      sourceRef:
        kind: HelmRepository
        name: pulsar
      version: 3.0.0
  interval: 1m0s
  values:
    volumes:
      persistence: false
    components:
      zookeeper: true
      bookkeeper: true
      autorecovery: true
      broker: true
      functions: false
      proxy: false
      toolset: false
      pulsar_manager: true
    monitoring:
      prometheus: false
      grafana: false
    initialize: true

```yaml
</code>```

Body:
reconciliation failed: Helm install failed: services is forbidden: User "system:serviceaccount:flux-system:helm-controller" cannot create resource "services" in API group │
│  "" in the namespace "kube-system": GKEAutopilot authz: the namespace "kube-system" is managed and the request's verb "create" is denied                                                                           │
│   Warning  error  21s  helm-controller  reconciliation failed: Operation cannot be fulfilled on helmreleases.helm.toolkit.fluxcd.io "pulsar": the object has been modified; please apply your changes to the lates │
│ t version and try again

Is there some option I could --set to avoid this?
Is there a component I have to disable to avoid this?

I'm trying to install pulsar via Helm and via flux.cd

My two sources are:

helmrepo.yaml

apiVersion: source.toolkit.fluxcd.io/v1beta2
kind: HelmRepository
metadata:
  name: pulsar
  namespace: pulsar
spec:
  interval: 1m0s
  url: https://pulsar.apache.org/charts

helmrelease.yaml

apiVersion: helm.toolkit.fluxcd.io/v2beta1
kind: HelmRelease
metadata:
  name: pulsar
  namespace: pulsar
spec:
  chart:
    spec:
      chart: pulsar
      sourceRef:
        kind: HelmRepository
        name: pulsar
      version: 3.0.0
  interval: 1m0s
  values:
    volumes:
      persistence: false
    components:
      zookeeper: true
      bookkeeper: true
      autorecovery: true
      broker: true
      functions: false
      proxy: false
      toolset: false
      pulsar_manager: true
    monitoring:
      prometheus: false
      grafana: false
    initialize: true

```yaml


问:
Symfony 5.4 Auto login after user confirmation and password reset
How Auto login after user confirmation and password reset using le link in the email sent?

I tried to use Password less login link but I'm not able to make a mix with emailverifierbundle...


问:
Text input elements returning 'undefined' to .csv file
EDIT: I figured the problem out. It had turned out I was appending the items to themselves. The correct method I worked out would be to make a new variable as such:
var form = document.getElementById("listItems");

and then editing the document.body.appendChild(itemName); to
form.appendChild(itemName) and  form.appendChild(itemQuantity) respectively.

For context, the call to the backend looked as such:

```<code>   <form action="/buy" method=post id="listItems">
    <input type="submit" value="Send">
  </form>
</code>```

When creating text boxes, I save the contents to a .csv file, however when I access these files I am returned a value of 'undefined'.

I looked into the code, and found that the input is saving itself as undefined no matter what was put in the text box.

Specifically these text boxes,

```<code><script>
  function addItems(){
    var itemName = document.createElement("input");
    itemName.setAttribute('type', 'text');
    itemName.placeholder = "itemName";
    document.body.appendChild(itemName);

    var itemQuantity = document.createElement("input");
    itemQuantity.setAttribute('type', 'text');
    itemQuantity.placeholder = "itemQuantity";
    document.body.appendChild(itemQuantity);

  }
  </script>
</code>```

var itemName and itemQuantity show up in console.log and in the file as undefined values.

What should've happened was that when I ran:

```<code>var itemN = req.body.itemName;
    var itemQ = req.body.itemQuantity;
    await fs.appendFile('receipt.csv', "\n" + itemN + " " + itemQ, err => {
        if (err) {
            console.error(err);
        }
        console.log(itemN, itemQ);
        // done!
    })
</code>```

It should have appended to the file 'receipt.csv' as ItemN + ItemQ as a string, however when accessed the file shows the submitted text as: Undefined Undefined.

Body:
EDIT: I figured the problem out. It had turned out I was appending the items to themselves. The correct method I worked out would be to make a new variable as such:
var form = document.getElementById("listItems");

and then editing the document.body.appendChild(itemName); to
form.appendChild(itemName) and  form.appendChild(itemQuantity) respectively.

For context, the call to the backend looked as such:

   <form action="/buy" method=post id="listItems">
    <input type="submit" value="Send">
  </form>

When creating text boxes, I save the contents to a .csv file, however when I access these files I am returned a value of 'undefined'.

I looked into the code, and found that the input is saving itself as undefined no matter what was put in the text box.

Specifically these text boxes,

var itemName and itemQuantity show up in console.log and in the file as undefined values.

What should've happened was that when I ran:

var itemN = req.body.itemName;
    var itemQ = req.body.itemQuantity;
    await fs.appendFile('receipt.csv', "\n" + itemN + " " + itemQ, err => {
        if (err) {
            console.error(err);
        }
        console.log(itemN, itemQ);
        // done!
    })

It should have appended to the file 'receipt.csv' as ItemN + ItemQ as a string, however when accessed the file shows the submitted text as: Undefined Undefined.


问:
NodeJS: gherkin-lint: How to make a binary from this node module?
I am currently working on a set of BDD tests using Gherkin and Python. In order to have standardized feature files I want to include a git hook for the repo.

I found a good linter, gherkin-lint, but it's all Node.js oriented and I don't want to have to install Node to use it. I tried to create a binary package out of it using the Node pkg module, but It is complaining about the bin entry on package.json.

# pkg . -o gherkin-lint
> pkg@5.8.0
> Error! Bin file does not exist (taken from package.json 'bin' property)
  /app/gherkin-lint/dist/main.js
```

I'm not a Node.js developer and don't have much knowledge of it. Is there a way to achieve what I'm trying to do?

Also, I found a formatter (reformat-gherkin) that is pre-commit oriented, but it is not a linter. It only formats the feature files indentation and doesn't look for bad-practices in the code, like duplicated tags, so it doesn't fit for what I'm trying to achieve.

Body:
I am currently working on a set of BDD tests using Gherkin and Python. In order to have standardized feature files I want to include a git hook for the repo.

I found a good linter, gherkin-lint, but it's all Node.js oriented and I don't want to have to install Node to use it. I tried to create a binary package out of it using the Node pkg module, but It is complaining about the bin entry on package.json.

# pkg . -o gherkin-lint
> pkg@5.8.0
> Error! Bin file does not exist (taken from package.json 'bin' property)
  /app/gherkin-lint/dist/main.js

I'm not a Node.js developer and don't have much knowledge of it. Is there a way to achieve what I'm trying to do?

Also, I found a formatter (reformat-gherkin) that is pre-commit oriented, but it is not a linter. It only formats the feature files indentation and doesn't look for bad-practices in the code, like duplicated tags, so it doesn't fit for what I'm trying to achieve.


问:
Snowflake: How to extract file name from the empty file
I have a requirement where input file name has to be captured and stored in the snowflake table. I am using snowflake snowpipe & stage to query the file which is in s3. My code/query works fine when the input file has data, however if the input file is empty, copy command is not getting the file name.

How to get the file name when the input file is empty/zero byte ? Thanks

Snowpipe syntax

CREATE OR REPLACE PIPE DEV.schema.load_pipe auto_ingest = true
AS
COPY INTO schema.TMP_table FROM (
    SELECT
      $1::variant AS MESSAGE,
      SPLIT_PART(METADATA$FILENAME,'/',4) AS FILE_NAME,
      current_timestamp::timestamp_ntz  as LOAD_TS
    FROM @DEV.STAGE.DEV_STG/input/
)
    pattern = 'File_DLYERR_.*'
```


问:
Renaming duplicate list names in R
Let's say that I have six data.tables that are contained in a two-level list as follows:
(Note - the values within the data.tables aren't important for the purpose of this exercise)

```<code>library(data.table)

DT_1 <- data.table(AA = 1)
DT_2 <- data.table(AB = 1)
DT_3 <- data.table(AC = 1)
DT_4 <- data.table(AD = 1)
DT_5 <- data.table(AE = 1)
DT_6 <- data.table(AF = 1)

# Create a list with two levels. The second layer contains the data.tables and may have
# duplicate names both within each list and between lists

List_check <- list(A = list(X = DT_1,X = DT_2,Y = DT_3),
                   B = list(X = DT_4,Y = DT_5,Z = DT_6))
</code>```

Essentially my code will create each of the data tables, and name them on the fly based on a timestamp in the format yyyymmddhhmmss.

The timestamp for the naming convention of the second list layer can't be more granular than seconds, so I'm finding that I'm coming up with duplicate names both within each list (e.g. we have two tables named "X" within list element A) and between lists (e.g. we have another table named "X" within list element B, as well as "Y" being a duplicate between lists A and B).

Also, the names of the top layer (A and B) can't be added to the names of the second layer of the list components (to potentially reduce duplicates). Other than that, I'm not constrained by having to have the list in two layers as all of the data tables are on the second layer of the list. Having said that, I must be able to know the relationship between the names of the top and second layer of the list as I need to save the second-layer tables to different folders later based on the values of A and B.

Ultimately, I want to rename all duplicate names in the second layer to make them unique, but still ensuring that they're in the required timestamp format.

For example, say that the names X, Y and Z referenced above were as follows:

```<code>library(lubridate)
X <- gsub("-|:| ","",dmy_hms("1/1/2023 9:00:00"))
Y <- gsub("-|:| ","",dmy_hms("1/1/2023 9:00:01"))
Z <- gsub("-|:| ","",dmy_hms("1/1/2023 9:00:02"))
</code>```

We have three instances where a list table is named 'X'. My initial thinking was that I could simply add 1, 2,... seconds to the duplicates within each duplicate grouping, however that would then potentially create new duplicates.

e.g. As we have three instances where the name is 'X', I would need to rename the second and third as follows:

```<code>X_1 <- gsub("-|:| ","",dmy_hms("1/1/2023 9:00:01"))
X_2 <- gsub("-|:| ","",dmy_hms("1/1/2023 9:00:02"))
</code>```

...however the problem is that X_1 = Y, and X_2 = Z so I've re-created duplicate names.

So my next view was that the pseudocode would be something like this:

Extract a data table containing two columns. Column 1 = names of the first layer, and Column 2 = names of the second layer. Something like this:

```<code> List_names = data.table(Top_layer = c(rep("A",3),rep("B",3)),
                        Bottom_layer = c("X","X","Y","X","Y","Z"))
</code>```

Check if there are any duplicate values in "Bottom_layer"

If so, create a third column <New_name> which starts from the first value in the 'Bottom_layer' column, and adds 1s to each previous value.

Rename the original list with the new names based on the column 'New_name'

In practice, my data set will have many dozens of names in each layer.
The first problem I had was that I can't find a simple way to do step (1) other than looping through each of the names using lapply() for example, extracting each of the names of that layer and then rbindlist(ing) it at the end.
Steps (2) and (3) are pretty easy once I have Step (1) sorted.

Secondly, I can't think of a simple way to do Step (4) other than repeating Step (1) and looping through each of the names of the first layer and changing the layer 2 names.

But most importantly, I feel that there must be a better method than this! Potentially with some of the list functions within the 'purrr' package?

Apologies for the very long explanation, but can anyone a) think of a better way to do this, and/or b) help me with the code for my draft approach outlined above?

Thanks heaps in advance,
Phil

EDIT

I've added a more concrete example together with what the output is that I'm hoping for.

Firstly, I'll change the names of the List_check table to reflect timestamps as intended:

```<code>names(List_check$A) <- c(X,X,Y) #Where X and Y are defined as timestamps above
names(List_check$B) <- c(X,Y,Z)
</code>```

To ensure that each are unique and to preserve the timestamp format of the names (in practice there's a character prefix, and then a timestamp - but for simplicity, just using a timestamp here), target output is such that the new list is:

```<code>List_check <- list(A = list(X1 = DT_1,X2 = DT_2,X3 = DT_3),
                   B = list(X4 = DT_4,X5 = DT_5,X6 = DT_6))
Where:
X1 <- gsub("-|:| ","",dmy_hms("1/1/2023 9:00:00"))
X2 <- gsub("-|:| ","",dmy_hms("1/1/2023 9:00:01"))
X3 <- gsub("-|:| ","",dmy_hms("1/1/2023 9:00:02"))
</code>```

etc etc

```<code>X6 <- gsub("-|:| ","",dmy_hms("1/1/2023 9:00:05"))
</code>```

In other words, if there is at least one duplicate, rename so that the timestamps increment by one second from the name of the first list element.

Please let me know if there are any questions.

Thanks again,
Phil

Title: Renaming duplicate list names in R

Body:
Let's say that I have six data.tables that are contained in a two-level list as follows:
(Note - the values within the data.tables aren't important for the purpose of this exercise)

library(data.table)

DT_1 <- data.table(AA = 1)
DT_2 <- data.table(AB = 1)
DT_3 <- data.table(AC = 1)
DT_4 <- data.table(AD = 1)
DT_5 <- data.table(AE = 1)
DT_6 <- data.table(AF = 1)

# Create a list with two levels. The second layer contains the data.tables and may have
# duplicate names both within each list and between lists

List_check <- list(A = list(X = DT_1,X = DT_2,Y = DT_3),
                   B = list(X = DT_4,Y = DT_5,Z = DT_6))

Essentially my code will create each of the data tables, and name them on the fly based on a timestamp in the format yyyymmddhhmmss.

The timestamp for the naming convention of the second list layer can't be more granular than seconds, so I'm finding that I'm coming up with duplicate names both within each list (e.g. we have two tables named "X" within list element A) and between lists (e.g. we have another table named "X" within list element B, as well as "Y" being a duplicate between lists A and B).

Also, the names of the top layer (A and B) can't be added to the names of the second layer of the list components (to potentially reduce duplicates). Other than that, I'm not constrained by having to have the list in two layers as all of the data tables are on the second layer of the list. Having said that, I must be able to know the relationship between the names of the top and second layer of the list as I need to save the second-layer tables to different folders later based on the values of A and B.

Ultimately, I want to rename all duplicate names in the second layer to make them unique, but still ensuring that they're in the required timestamp format.

For example, say that the names X, Y and Z referenced above were as follows:

library(lubridate)
X <- gsub("-|:| ","",dmy_hms("1/1/2023 9:00:00"))
Y <- gsub("-|:| ","",dmy_hms("1/1/2023 9:00:01"))
Z <- gsub("-|:| ","",dmy_hms("1/1/2023 9:00:02"))

We have three instances where a list table is named 'X'. My initial thinking was that I could simply add 1, 2,... seconds to the duplicates within each duplicate grouping, however that would then potentially create new duplicates.

e.g. As we have three instances where the name is 'X', I would need to rename the second and third as follows:

X_1 <- gsub("-|:| ","",dmy_hms("1/1/2023 9:00:01"))
X_2 <- gsub("-|:| ","",dmy_hms("1/1/2023 9:00:02"))

...however the problem is that X_1 = Y, and X_2 = Z so I've re-created duplicate names.

So my next view was that the pseudocode would be something like this:

Extract a data table containing two columns. Column 1 = names of the first layer, and Column 2 = names of the second layer. Something like this:

 List_names = data.table(Top_layer = c(rep("A",3),rep("B",3)),
                        Bottom_layer = c("X","X","Y","X","Y","Z"))

Check if there are any duplicate values in "Bottom_layer"

If so, create a third column <New_name> which starts from the first value in the 'Bottom_layer' column, and adds 1s to each previous value.

Rename the original list with the new names based on the column 'New_name'

In practice, my data set will have many dozens of names in each layer.
The first problem I had was that I can't find a simple way to do step (1) other than looping through each of the names using lapply() for example, extracting each of the names of that layer and then rbindlist(ing) it at the end.
Steps (2) and (3) are pretty easy once I have Step (1) sorted.

Secondly, I can't think of a simple way to do Step (4) other than repeating Step (1) and looping through each of the names of the first layer and changing the layer 2 names.

But most importantly, I feel that there must be a better method than this! Potentially with some of the list functions within the 'purrr' package?

Apologies for the very long explanation, but can anyone a) think of a better way to do this, and/or b) help me with the code for my draft approach outlined above?

Thanks heaps in advance,
Phil

EDIT

I've added a more concrete example together with what the output is that I'm hoping for.

Firstly, I'll change the names of the List_check table to reflect timestamps as intended:

names(List_check$A) <- c(X,X,Y) #Where X and Y are defined as timestamps above
names(List_check$B) <- c(X,Y,Z)

To ensure that each are unique and to preserve the timestamp format of the names (in practice there's a character prefix, and then a timestamp - but for simplicity, just using a timestamp here), target output is such that the new list is:

List_check <- list(A = list(X1 = DT_1,X2 = DT_2,X3 = DT_3),
                   B = list(X4 = DT_4,X5 = DT_5,X6 = DT_6))
Where:
X1 <- gsub("-|:| ","",dmy_hms("1/1/2023 9:00:00"))
X2 <- gsub("-|:| ","",dmy_hms("1/1/2023 9:00:01"))
X3 <- gsub("-|:| ","",dmy_hms("1/1/2023 9:00:02"))

etc etc

X6 <- gsub("-|:| ","",dmy_hms("1/1/2023 9:00:05"))

In other words, if there is at least one duplicate, rename so that the timestamps increment by one second from the name of the first list element.

Please let me know if there are any questions.

Thanks again,
Phil


问:
How to define a function of callbacks where callback N's argument is the merge of the N-1 callback return types
Below, specialFunction takes N callbacks and constrains them such that each callback's only argument is the merge of the N-1 callback return types. My goal is to avoid hardcoding the number of arguments that specialFunction takes.

const specialFunction = <something>
specialFunction(
  () => ({a: 1}),
  (arg) => {
    console.log(arg.a)
    return { b: 2}
  }),
  (arg) => {
    console.log(arg.a)
    console.log(arg.b)
  }
) // does not error
specialFunction(
  () => ({a: 1}),
  (arg) => {
    console.log(arg.b)
    return { b: 2}
  }),
  (arg) => {
    console.log(arg.a)
    console.log(arg.c) // typescript error here
  }
)
```
<p>But I am not sure how to proceed to make this possible.</p>
<p>I've tried this so far, but it doesn't work</p>
<pre class="lang-js prettyprint-override"><code>type MergeArr<Arr extends unknown[], Merged = void> =
  Arr['length'] extends 0 ?
  Merged :
  Arr extends [infer Head, ...infer Tail] ?
  MergeArr<Tail,
    {[key in keyof Merged | keyof Head] :
        key extends keyof Head ?
        Head[key] :
        key extends keyof Merged ? Merged[key] : never
    }> :
  never

type Take<Arr extends readonly unknown[], N extends `${number}` | number, Until extends unknown[] = []> =
  `${Until['length']}` extends N ?
  Until :
  Until['length'] extends N ?
  Until :
  Arr extends [infer Head, ...infer Tail] ?
  Take<Tail, N, [...Until, Head]> :
  never
const specialFunction = <T extends unknown[]>
(
  ...args:
  {
    [K in keyof T] : (
      params: MergeArr<Take<T, K>>
    ) => T[K]
  }
) => true
specialFunction(() => ({a:2}), ({a}) => ({b: 2}), ({b}) => ({c: 3})) // errors at third argument
</code>```

Body:
Below, specialFunction takes N callbacks and constrains them such that each callback's only argument is the merge of the N-1 callback return types. My goal is to avoid hardcoding the number of arguments that specialFunction takes.

const specialFunction = <something>
specialFunction(
  () => ({a: 1}),
  (arg) => {
    console.log(arg.a)
    return { b: 2}
  }),
  (arg) => {
    console.log(arg.a)
    console.log(arg.b)
  }
) // does not error
specialFunction(
  () => ({a: 1}),
  (arg) => {
    console.log(arg.b)
    return { b: 2}
  }),
  (arg) => {
    console.log(arg.a)
    console.log(arg.c) // typescript error here
  }
)

But I am not sure how to proceed to make this possible.

I've tried this so far, but it doesn't work

type MergeArr<Arr extends unknown[], Merged = void> =
  Arr['length'] extends 0 ?
  Merged :
  Arr extends [infer Head, ...infer Tail] ?
  MergeArr<Tail,
    {[key in keyof Merged | keyof Head] :
        key extends keyof Head ?
        Head[key] :
        key extends keyof Merged ? Merged[key] : never
    }> :
  never

type Take<Arr extends readonly unknown[], N extends `${number}` | number, Until extends unknown[] = []> =
  `${Until['length']}` extends N ?
  Until :
  Until['length'] extends N ?
  Until :
  Arr extends [infer Head, ...infer Tail] ?
  Take<Tail, N, [...Until, Head]> :
  never
const specialFunction = <T extends unknown[]>
(
  ...args:
  {
    [K in keyof T] : (
      params: MergeArr<Take<T, K>>
    ) => T[K]
  }
) => true
specialFunction(() => ({a:2}), ({a}) => ({b: 2}), ({b}) => ({c: 3})) // errors at third argument


问:
Read accented letters php in the statement
this if statement doesn't read me the accented letters:

if( $f_name === 'Cà') $f_name = 'SSD';

I also tried with:

if( $f_name === 'Cà') $f_name = 'SSD';

but nothing...

How can I fix?
Thank you


问:
How do I install pattern lab node from scratch?
I have node.js installed as well as nvm to switch versions easily.

I would like to install pattern lab 3.0.0 node edition using mustache with some basic vanilla starter kit patterns to get me going.

I’ve used pattern lab 2.02 webpack version previously and I am familiar with how to use it once it is up and running.

Following the instructions on GitHub does not yield results as any commands I invoke throw errors. I would love to have a step by step list of every command I need to type in the terminal to successfully install and run a basic version of pattern lab where it opens a browser with some patterns, so I can start editing and see the updates in the browser to start building out a new system.

I’ve tried installing the core and the cli separately, as well as several editions which claim to have the basic scripts loaded for initialization. Running any of the commands such as pl:build, npm run patternlab, npm create pattern-lab, npm run start, npm start etc. all of these just end in the terminal giving errors where they say the commands are not available. I’ve tried to add these commands under the scripts section of my package.json but still no luck in running pattern lab.


问:
Dynamically renaming attributes of a python class?
I am working with a beta version of a python library that has renamed a few of the class functions, for instance from "isConnected" to "is_connected". I have different servers with different versions of this library on them and it tends to get annoying to deal with. So far I have till now been dealing with it like:

```<code>try:
    from eth_utils.conversions import toHex as to_hex
except ImportError:
    from eth_utils.conversions import to_hex
</code>```

But this obviously isn't ideal. What I would like to be able to do is something like this:

```<code>is_beta = hasattr(eth_utils.conversions, 'to_hex')
if not is_beta:
    setattr(eth_utils.conversions, 'toHex', 'to_hex')
</code>```

How can this be done? I am guessing that it involves using some metaclass magic?

Edit: The reason why I am looking for a different method here is because I need to initialize web3 like this:

```<code>w3 = web3.Web3(web3.HTTPProvider(os.environ.get('ethereum_http_endpoint')))
</code>```

Then I need to call w3.is_connected:

```<code>if w3.is_connected:
    print('Web3 is connected ... now I can do stuff')
else:
    print('Not connected, something wrong, do something else')
</code>```

So I can't just call is_connected because I specifically need to call the attribute of the object which is created.

Body:
I am working with a beta version of a python library that has renamed a few of the class functions, for instance from "isConnected" to "is_connected". I have different servers with different versions of this library on them and it tends to get annoying to deal with. So far I have till now been dealing with it like:

try:
    from eth_utils.conversions import toHex as to_hex
except ImportError:
    from eth_utils.conversions import to_hex

But this obviously isn't ideal. What I would like to be able to do is something like this:

is_beta = hasattr(eth_utils.conversions, 'to_hex')
if not is_beta:
    setattr(eth_utils.conversions, 'toHex', 'to_hex')

How can this be done? I am guessing that it involves using some metaclass magic?

Edit: The reason why I am looking for a different method here is because I need to initialize web3 like this:

w3 = web3.Web3(web3.HTTPProvider(os.environ.get('ethereum_http_endpoint')))

Then I need to call w3.is_connected:

if w3.is_connected:
    print('Web3 is connected ... now I can do stuff')
else:
    print('Not connected, something wrong, do something else')

So I can't just call is_connected because I specifically need to call the attribute of the object which is created.


问:
test environment does not support `mocked`
I'm writing some tests for a React Native app written in TS and currently trying to migrate to jest.mocked instead of using the mocked export from ts-jest/utils (which is required in order to move past jest v27). I get the following error though and have tried all sorts of things to try and fix it, but with no luck.

    Your test environment does not support `mocked`, please update it.

      54 |
      55 |   beforeEach(() => {
    > 56 |     jest.mocked(Icon).mockReturnValue(null)
         |          ^
      57 |   })
      58 |
      59 |   afterEach(() => {

      at Object.mocked (node_modules/jest-runtime/build/index.js:2204:19)
```
<pre class="lang-js prettyprint-override"><code>// babel.config.js
module.exports = {
  plugins: [
    [
      'module-resolver',
      {
        extensions: ['.js', '.jsx', '.ts', '.tsx'],
        root: ['.'],
      },
    ],
    'transform-inline-environment-variables',
    ['@babel/plugin-proposal-decorators', { legacy: true }],
    'react-native-reanimated/plugin',
  ],
  presets: [
    'module:metro-react-native-babel-preset',
    ['@babel/preset-react', { runtime: 'automatic' }],
  ],
}
</code>```

// jest.config.js
module.exports = {
  preset: 'react-native',
  collectCoverage: false,
  coveragePathIgnorePatterns: ['/node_modules/', '.*.test..*'],
  coverageReporters: ['text'],
  coverageThreshold: {
    global: {
      branches: 100,
    },
  },
  forceExit: true,
  globals: {
    'ts-jest': {
      babelConfig: '<rootDir>/babel.config.js',
      diagnostics: false,
      isolatedModules: true,
    },
  },
  moduleFileExtensions: [
    'gql',
    'ts',
    'tsx',
    'js',
    'jsx',
    'json',
    'node',
    'csv',
  ],
  modulePaths: ['<rootDir>'],
  modulePathIgnorePatterns: modulesToIgnore,
  resetMocks: false,
  resetModules: false,
  setupFilesAfterEnv: ['<rootDir>/__tests__/setup/index.ts'],
  testMatch: [
    '<rootDir>/__tests__/**/*.test.ts?(x)',
    '<rootDir>/src/**/?(*.)test.ts?(x)',
  ],
  testPathIgnorePatterns: ['<rootDir>/node_modules', ...modulesToIgnore],
  transform: {
    '^.+\\.jsx?$': 'babel-jest',
    '^.+\\.tsx?$': 'ts-jest',
  },
  transformIgnorePatterns: [
    `<rootDir>/node_modules/(?!${modulesNeedingTransform.join('|')})`,
  ],
  verbose: true,
}
```

Nothing is standing out to me as immediately obvious for what's keeping jest.mocked from being available.

Body:
I'm writing some tests for a React Native app written in TS and currently trying to migrate to jest.mocked instead of using the mocked export from ts-jest/utils (which is required in order to move past jest v27). I get the following error though and have tried all sorts of things to try and fix it, but with no luck.

    Your test environment does not support `mocked`, please update it.

      54 |
      55 |   beforeEach(() => {
    > 56 |     jest.mocked(Icon).mockReturnValue(null)
         |          ^
      57 |   })
      58 |
      59 |   afterEach(() => {

      at Object.mocked (node_modules/jest-runtime/build/index.js:2204:19)

// babel.config.js
module.exports = {
  plugins: [
    [
      'module-resolver',
      {
        extensions: ['.js', '.jsx', '.ts', '.tsx'],
        root: ['.'],
      },
    ],
    'transform-inline-environment-variables',
    ['@babel/plugin-proposal-decorators', { legacy: true }],
    'react-native-reanimated/plugin',
  ],
  presets: [
    'module:metro-react-native-babel-preset',
    ['@babel/preset-react', { runtime: 'automatic' }],
  ],
}

// jest.config.js
module.exports = {
  preset: 'react-native',
  collectCoverage: false,
  coveragePathIgnorePatterns: ['/node_modules/', '.*.test..*'],
  coverageReporters: ['text'],
  coverageThreshold: {
    global: {
      branches: 100,
    },
  },
  forceExit: true,
  globals: {
    'ts-jest': {
      babelConfig: '<rootDir>/babel.config.js',
      diagnostics: false,
      isolatedModules: true,
    },
  },
  moduleFileExtensions: [
    'gql',
    'ts',
    'tsx',
    'js',
    'jsx',
    'json',
    'node',
    'csv',
  ],
  modulePaths: ['<rootDir>'],
  modulePathIgnorePatterns: modulesToIgnore,
  resetMocks: false,
  resetModules: false,
  setupFilesAfterEnv: ['<rootDir>/__tests__/setup/index.ts'],
  testMatch: [
    '<rootDir>/__tests__/**/*.test.ts?(x)',
    '<rootDir>/src/**/?(*.)test.ts?(x)',
  ],
  testPathIgnorePatterns: ['<rootDir>/node_modules', ...modulesToIgnore],
  transform: {
    '^.+\\.jsx?$': 'babel-jest',
    '^.+\\.tsx?$': 'ts-jest',
  },
  transformIgnorePatterns: [
    `<rootDir>/node_modules/(?!${modulesNeedingTransform.join('|')})`,
  ],
  verbose: true,
}

Nothing is standing out to me as immediately obvious for what's keeping jest.mocked from being available.


问:
How to define an argument's type as the associated type of a discriminated type in TypeScript?
I'm not sure how best to describe the problem aside from providing an example. Basically, is it possible to do something like this in TypeScript:

```<code>interface A {
  type: 'a',
  value: number,
}

interface B {
  type: 'b',
  value: string,
}

type Both = A|B;

function example(arg: Both, val: Both['value']) {
  // ...
}
</code>```

such that the TypeScript compiler ensures/knows that when arg: A then val must be a number (and when arg: B then val must be a `string). Is this possible?

Right now the best I can come up with is manually doing something like:

```<code>if (arg.type == 'a') {
  something(val as number);
}
</code>```

but this would still let the following problematic code compile:

```<code>let a: A = {
  type: 'a',
  value: 0
}
example(a, 'not a number');
</code>```

Update: I was able to get my original example working with the following:

```<code>export function example<T extends Both>(arg: T, val: typeof arg['value']) {
  arg.value = val;
}

let a: A = {
  type: 'a',
  value: 0
}
let b: B = {
  type: 'b',
  value: 'foo',
}
example(a, 0)
example(b, 'foo')
example(a, 'foo') // won't compile
example(b, 0)     // won't compile
</code>```

So typescript knows that val must match the type of arg.value.

However I came up with a better case that demonstrates what my actual problem is:

```<code>export function acceptsOnlyString(arg: string) {}
export function acceptsOnlyNumber(arg: number) {}

export function example<T extends Both>(arg: T, val: typeof arg['value']) {
  if (arg.type == 'a') {
    acceptsOnlyNumber(arg.value);
    acceptsOnlyNumber(val); // won't compile, val is still type string|number
  } else if (arg.type == 'b') {
    acceptsOnlyString(arg.value);
    acceptsOnlyString(val); // won't compile, val is still type string|number
  }
}
</code>```

My hope was that TypeScript would be able to infer the specific type of val, especially because the compiler rejects cases where arg.value and val have different types.

Body:
I'm not sure how best to describe the problem aside from providing an example. Basically, is it possible to do something like this in TypeScript:

interface A {
  type: 'a',
  value: number,
}

interface B {
  type: 'b',
  value: string,
}

type Both = A|B;

function example(arg: Both, val: Both['value']) {
  // ...
}

such that the TypeScript compiler ensures/knows that when arg: A then val must be a number (and when arg: B then val must be a `string). Is this possible?

Right now the best I can come up with is manually doing something like:

if (arg.type == 'a') {
  something(val as number);
}

but this would still let the following problematic code compile:

let a: A = {
  type: 'a',
  value: 0
}
example(a, 'not a number');

Update: I was able to get my original example working with the following:

export function example<T extends Both>(arg: T, val: typeof arg['value']) {
  arg.value = val;
}

let a: A = {
  type: 'a',
  value: 0
}
let b: B = {
  type: 'b',
  value: 'foo',
}
example(a, 0)
example(b, 'foo')
example(a, 'foo') // won't compile
example(b, 0)     // won't compile

So typescript knows that val must match the type of arg.value.

However I came up with a better case that demonstrates what my actual problem is:

export function acceptsOnlyString(arg: string) {}
export function acceptsOnlyNumber(arg: number) {}

export function example<T extends Both>(arg: T, val: typeof arg['value']) {
  if (arg.type == 'a') {
    acceptsOnlyNumber(arg.value);
    acceptsOnlyNumber(val); // won't compile, val is still type string|number
  } else if (arg.type == 'b') {
    acceptsOnlyString(arg.value);
    acceptsOnlyString(val); // won't compile, val is still type string|number
  }
}

My hope was that TypeScript would be able to infer the specific type of val, especially because the compiler rejects cases where arg.value and val have different types.


问:
INTEL MKL ERROR with reading CSV file in Python?
I am trying to read and parse a CSV file, but I get an unexpected issue related to Anaconda.

Below you will find the code that is used to open the CSV file:

```<code>import json
import csv
import random

def set_up_healthcare():

    hospitalWorkerList = []

    with open('data/healthcare_workers.csv', newline='') as csvfile:

        reader = csv.DictReader(csvfile)

        for row in reader:

            ageRow = row['Please indicate your age']
            genderRow = row['Gender']
            indianTerritoryRow = row['Please indicate which Indian State/Union territory you are currently residing in']
            educationRow = row['Educational qualification']
            maritalStatusRow = row['Marital status']
            covidPositiveRow = row['Are you currently COVID-19 positive? ']
            knowSomeoneCovidRow = row['Do you know any family member(s) or friend(s) who has/have tested positive for COVID-19?']
            anxietyDisorderRow = row['Have you ever been diagnosed with any anxiety disorder by a health worker like a psychiatrist/psychologist/counselor before?']
            adequateHospitalProtectionRow = row['The hospital has provided me with adequate personal protective equipment']
            feelDizzyRow = row['"I felt dizzy, lightheaded, or faint, when I read or listened to news about the coronavirus."']
            familyFearRow = row['My family expresses fear towards my work.']

            myHopsitalWorker = HealthcareWorker(age=ageRow, gender=genderRow, indianTerritory=indianTerritoryRow, education=educationRow, maritalStatus=maritalStatusRow, covidPositive=covidPositiveRow,
                                               knowSomeoneCovid=knowSomeoneCovidRow,anxietyDisorder=anxietyDisorderRow, feelDizzy=feelDizzyRow,
                                               adequateHospitalProtection=adequateHospitalProtectionRow, familyFear=familyFearRow)

            hospitalWorkerList.append(myHopsitalWorker)
</code>```

The error that I get is:

INTEL MKL ERROR: dlopen(/Users/marcelomorales/opt/anaconda3/lib/libmkl_core.1.dylib, 0x0009): tried: '/Users/marcelomorales/opt/anaconda3/lib/libmkl_core.1.dylib' (no such file).
Intel MKL FATAL ERROR: Cannot load libmkl_core.1.dylib.
```
<p>For context, below is information regarding my operating system:</p>
<pre class="lang-none prettyprint-override"><code>Darwin Marcelos-MacBook-Pro.local 21.6.0 Darwin Kernel Version 21.6.0: Mon Aug 22 20:17:10 PDT 2022; root:xnu-8020.140.49~2/RELEASE_X86_64 x86_64
</code>```

Body:
I am trying to read and parse a CSV file, but I get an unexpected issue related to Anaconda.

Below you will find the code that is used to open the CSV file:

import json
import csv
import random

def set_up_healthcare():

    hospitalWorkerList = []

    with open('data/healthcare_workers.csv', newline='') as csvfile:

        reader = csv.DictReader(csvfile)

        for row in reader:

            ageRow = row['Please indicate your age']
            genderRow = row['Gender']
            indianTerritoryRow = row['Please indicate which Indian State/Union territory you are currently residing in']
            educationRow = row['Educational qualification']
            maritalStatusRow = row['Marital status']
            covidPositiveRow = row['Are you currently COVID-19 positive? ']
            knowSomeoneCovidRow = row['Do you know any family member(s) or friend(s) who has/have tested positive for COVID-19?']
            anxietyDisorderRow = row['Have you ever been diagnosed with any anxiety disorder by a health worker like a psychiatrist/psychologist/counselor before?']
            adequateHospitalProtectionRow = row['The hospital has provided me with adequate personal protective equipment']
            feelDizzyRow = row['"I felt dizzy, lightheaded, or faint, when I read or listened to news about the coronavirus."']
            familyFearRow = row['My family expresses fear towards my work.']

            myHopsitalWorker = HealthcareWorker(age=ageRow, gender=genderRow, indianTerritory=indianTerritoryRow, education=educationRow, maritalStatus=maritalStatusRow, covidPositive=covidPositiveRow,
                                               knowSomeoneCovid=knowSomeoneCovidRow,anxietyDisorder=anxietyDisorderRow, feelDizzy=feelDizzyRow,
                                               adequateHospitalProtection=adequateHospitalProtectionRow, familyFear=familyFearRow)

            hospitalWorkerList.append(myHopsitalWorker)

The error that I get is:

INTEL MKL ERROR: dlopen(/Users/marcelomorales/opt/anaconda3/lib/libmkl_core.1.dylib, 0x0009): tried: '/Users/marcelomorales/opt/anaconda3/lib/libmkl_core.1.dylib' (no such file).
Intel MKL FATAL ERROR: Cannot load libmkl_core.1.dylib.

For context, below is information regarding my operating system:

Darwin Marcelos-MacBook-Pro.local 21.6.0 Darwin Kernel Version 21.6.0: Mon Aug 22 20:17:10 PDT 2022; root:xnu-8020.140.49~2/RELEASE_X86_64 x86_64


问:
Twilio Second Gather in Node.js getting cutoff for some reason
```<code>const VoiceResponse = require('twilio').twiml.VoiceResponse;
const urlencoded = require('body-parser').urlencoded;
const app = express();
var user;
var pass;

// Parse incoming POST params with Express middleware
app.use(urlencoded({ extended: false }));

// Create a route that will handle Twilio webhook requests, sent as an
// HTTP POST to /voice in our application
app.post('/voice', (request, response) => {
 // Use the Twilio Node.js SDK to build an XML response
 const twiml = new VoiceResponse();

 // Use the <Gather> verb to collect user input
 const gather = twiml.gather({
   numDigits: 3,
   action: '/gather',
 });
 gather.say('Enter UserID.');

 // If the user doesn't enter input, loop
 twiml.redirect('/voice');

 // Render the response as XML in reply to the webhook request
 response.type('text/xml');
 response.send(twiml.toString());
});

// Create a route that will handle <Gather> input
app.post('/gather', (request1, response1) => {
   // Use the Twilio Node.js SDK to build an XML response
   const twiml1 = new VoiceResponse();
   // If the user entered digits, process their request
   if (request1.body.Digits) {

       user = JSON.stringify(request1.body.Digits);

       // Use the <Gather> verb to collect user input
       const gather2 = twiml1.gather({
           numDigits: 2,
         action: '/validate',
       });
       gather2.say('Enter Password.');

   } else {
     // If no input was sent, redirect to the /voice route
     twiml1.redirect('/voice');
   }

   // Render the response as XML in reply to the webhook request
   response1.type('text/xml');
   response1.send(twiml1.toString());
 });

// Create a route that will handle Second <Gather> input
app.post('/validate', (request2, response2) => {
   // Use the Twilio Node.js SDK to build an XML response
   const twiml2 = new VoiceResponse();

   // If the user entered digits, process their request
   if (request2.body.Digits) {

       pass = JSON.stringify(request2.body.Digits);

       twiml2.say('Your username is ' + user + '.Your password is' + pass + '. Goodbye!');

   } else {
     // If no input was sent, redirect to the /voice route
     twiml2.redirect('/voice');
   }

   // Render the response as XML in reply to the webhook request
   response2.type('text/xml');
   response2.send(twiml2.toString());
 });
// Create an HTTP server and listen for requests on port 1337
console.log('Twilio Client app HTTP server running at http://127.0.0.1:1337');
app.listen(1337);
</code>```

Currently I'm writing an application with Twilio Voice that takes users username and password which are two numbers of length 3 and 2 respectively and says it back to them, written in Node.js. The first gather goes through just fine, however during the call, it cuts off during the twiml saying "Enter Password". It says "Enter Pass-" and the call abruptly ends for some reason. I have configured the ngrok address in the client and added /voice to the end of the address. What could be the cause for this? I have speculated there is a problem with assigning the variable user and pass the users digits due to timeout.

Body:
const VoiceResponse = require('twilio').twiml.VoiceResponse;
const urlencoded = require('body-parser').urlencoded;
const app = express();
var user;
var pass;

// Parse incoming POST params with Express middleware
app.use(urlencoded({ extended: false }));

// Create a route that will handle Twilio webhook requests, sent as an
// HTTP POST to /voice in our application
app.post('/voice', (request, response) => {
 // Use the Twilio Node.js SDK to build an XML response
 const twiml = new VoiceResponse();

 // Use the <Gather> verb to collect user input
 const gather = twiml.gather({
   numDigits: 3,
   action: '/gather',
 });
 gather.say('Enter UserID.');

 // If the user doesn't enter input, loop
 twiml.redirect('/voice');

 // Render the response as XML in reply to the webhook request
 response.type('text/xml');
 response.send(twiml.toString());
});

// Create a route that will handle <Gather> input
app.post('/gather', (request1, response1) => {
   // Use the Twilio Node.js SDK to build an XML response
   const twiml1 = new VoiceResponse();
   // If the user entered digits, process their request
   if (request1.body.Digits) {

       user = JSON.stringify(request1.body.Digits);

       // Use the <Gather> verb to collect user input
       const gather2 = twiml1.gather({
           numDigits: 2,
         action: '/validate',
       });
       gather2.say('Enter Password.');

   } else {
     // If no input was sent, redirect to the /voice route
     twiml1.redirect('/voice');
   }

   // Render the response as XML in reply to the webhook request
   response1.type('text/xml');
   response1.send(twiml1.toString());
 });

// Create a route that will handle Second <Gather> input
app.post('/validate', (request2, response2) => {
   // Use the Twilio Node.js SDK to build an XML response
   const twiml2 = new VoiceResponse();

   // If the user entered digits, process their request
   if (request2.body.Digits) {

       pass = JSON.stringify(request2.body.Digits);

       twiml2.say('Your username is ' + user + '.Your password is' + pass + '. Goodbye!');

   } else {
     // If no input was sent, redirect to the /voice route
     twiml2.redirect('/voice');
   }

   // Render the response as XML in reply to the webhook request
   response2.type('text/xml');
   response2.send(twiml2.toString());
 });
// Create an HTTP server and listen for requests on port 1337
console.log('Twilio Client app HTTP server running at http://127.0.0.1:1337');
app.listen(1337);

Currently I'm writing an application with Twilio Voice that takes users username and password which are two numbers of length 3 and 2 respectively and says it back to them, written in Node.js. The first gather goes through just fine, however during the call, it cuts off during the twiml saying "Enter Password". It says "Enter Pass-" and the call abruptly ends for some reason. I have configured the ngrok address in the client and added /voice to the end of the address. What could be the cause for this? I have speculated there is a problem with assigning the variable user and pass the users digits due to timeout.


问:
How to declare a clone method returns a writable copy in Typescript?
Let's imagine I want to declare an interface, that contains a clone methods, that returns a mutable clone, even if this object is Readonly.

Can it be done in Typescript? Seems rather a trivial case to me.

Let's imagine following interface. For our purposes, slice is the "clone" method in question, so our interface is trivially implemented by any Array or TypedArray. I am using generics because I want that my code my code to work correctly in both cases.

```<code>export interface ArrayLike {
    [index: number]: number
    length: number
    slice(): this
}
</code>```

However it doesn't work as expected. Following code does not compile:

```<code>function clone<T extends ArrayLike>(array: Readonly<T>): T {
    return array.slice()
}
</code>```

Error message says:

```<code>Type 'ArrayLike' is not assignable to type 'T'.
  'ArrayLike' is assignable to the constraint of type 'T',
  but 'T' could be instantiated with a different subtype
  of constraint 'ArrayLike'.ts(2322)
</code>```

Another attempt would be something like this: (spoiler alert: does not work either)

```<code>export type Writeable<T> = { -readonly [P in keyof T]: T[P] }
export interface AnotherAttemptArrayLike {
    [index: number]: number
    length: number
    slice(): Writeable<this>
}

function anotherAttemptClone<T extends AnotherAttemptArrayLike>(array: Readonly<T>): T {
    return array.slice()
}
</code>```

The error message says the following:

```<code>Type 'Writeable<AnotherAttemptArrayLike>' is not assignable to type 'T'.
'T' could be instantiated with an arbitrary type which could be
unrelated to  'Writeable<AnotherAttemptArrayLike>'.ts(2322)
</code>```

Persoanally I don't believe this case doesn't have a clean Typescript solution, so I am asking for help here. Cheers.

Body:
Let's imagine I want to declare an interface, that contains a clone methods, that returns a mutable clone, even if this object is Readonly.

Can it be done in Typescript? Seems rather a trivial case to me.

Let's imagine following interface. For our purposes, slice is the "clone" method in question, so our interface is trivially implemented by any Array or TypedArray. I am using generics because I want that my code my code to work correctly in both cases.

export interface ArrayLike {
    [index: number]: number
    length: number
    slice(): this
}

However it doesn't work as expected. Following code does not compile:

function clone<T extends ArrayLike>(array: Readonly<T>): T {
    return array.slice()
}

Error message says:

Type 'ArrayLike' is not assignable to type 'T'.
  'ArrayLike' is assignable to the constraint of type 'T',
  but 'T' could be instantiated with a different subtype
  of constraint 'ArrayLike'.ts(2322)

Another attempt would be something like this: (spoiler alert: does not work either)

export type Writeable<T> = { -readonly [P in keyof T]: T[P] }
export interface AnotherAttemptArrayLike {
    [index: number]: number
    length: number
    slice(): Writeable<this>
}

function anotherAttemptClone<T extends AnotherAttemptArrayLike>(array: Readonly<T>): T {
    return array.slice()
}

The error message says the following:

Type 'Writeable<AnotherAttemptArrayLike>' is not assignable to type 'T'.
'T' could be instantiated with an arbitrary type which could be
unrelated to  'Writeable<AnotherAttemptArrayLike>'.ts(2322)

Persoanally I don't believe this case doesn't have a clean Typescript solution, so I am asking for help here. Cheers.


问:
node:internal/modules/cjs/loader:988 throw err
I am attempting to deploy my MERN application to Heroku however when I type  heroku local in the terminal to check if everything is good to go I am getting the following error.

```<code>7:32:28 PM web.1 |  node:internal/modules/cjs/loader:988
7:32:28 PM web.1 |    throw err;
7:32:28 PM web.1 |    ^
7:32:28 PM web.1 |  Error: Cannot find module '/Users/evmacbook/Desktop/bootcamp/Personal Projects/travelX/server.js,'
7:32:28 PM web.1 |      at Function.Module._resolveFilename (node:internal/modules/cjs/loader:985:15)
7:32:28 PM web.1 |      at Function.Module._load (node:internal/modules/cjs/loader:833:27)
7:32:28 PM web.1 |      at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
7:32:28 PM web.1 |      at node:internal/main/run_main_module:22:47 {
7:32:28 PM web.1 |    code: 'MODULE_NOT_FOUND',
7:32:28 PM web.1 |    requireStack: []
7:32:28 PM web.1 |  }
[DONE] Killing all processes with signal  SIGINT
7:32:28 PM web.1 Exited with exit code null
</code>```

Image of my folder structure

My server.js file is located inside my server folder. My server folder is located in the root folder. I have uninstalled and reinstalled all my package.json packages multiple times and that does not seem to help. It does seem to look like that node is attempting to locate the server.js file in the root folder and not in the server folder. However even when i try placing the server.js in the root folder just to test it out I still seem to get this same error.

Body:
I am attempting to deploy my MERN application to Heroku however when I type  heroku local in the terminal to check if everything is good to go I am getting the following error.

7:32:28 PM web.1 |  node:internal/modules/cjs/loader:988
7:32:28 PM web.1 |    throw err;
7:32:28 PM web.1 |    ^
7:32:28 PM web.1 |  Error: Cannot find module '/Users/evmacbook/Desktop/bootcamp/Personal Projects/travelX/server.js,'
7:32:28 PM web.1 |      at Function.Module._resolveFilename (node:internal/modules/cjs/loader:985:15)
7:32:28 PM web.1 |      at Function.Module._load (node:internal/modules/cjs/loader:833:27)
7:32:28 PM web.1 |      at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
7:32:28 PM web.1 |      at node:internal/main/run_main_module:22:47 {
7:32:28 PM web.1 |    code: 'MODULE_NOT_FOUND',
7:32:28 PM web.1 |    requireStack: []
7:32:28 PM web.1 |  }
[DONE] Killing all processes with signal  SIGINT
7:32:28 PM web.1 Exited with exit code null

Image of my folder structure

My server.js file is located inside my server folder. My server folder is located in the root folder. I have uninstalled and reinstalled all my package.json packages multiple times and that does not seem to help. It does seem to look like that node is attempting to locate the server.js file in the root folder and not in the server folder. However even when i try placing the server.js in the root folder just to test it out I still seem to get this same error.


问:
It is possible to find out the final stream url of an m3u file?
It is possible to find out the final stream url of an m3u file.
E.g. m3u file url is http://server.address:8000/544.m3u and this url is streaming from e.g. https://youtuxxx.com/trgghh.m3u

Foolowing redirects


问:
Trying to SIGN manually created JWT assertion with Azure KeyVault certificate, Getting ERROR "content of "Value" is not base64url"
I am trying to manually create a JWT Assersion using certificate from Azure KeyVault.

I have my Base64 encoded Header & Base64 encoded Payload, and
I concatenated them with a "." But when trying to sign the whole string using the SIGN api (https://learn.microsoft.com/en-us/rest/api/keyvault/keys/sign/sign) getting the error "content of 'Value' is not base64url" which is expected as the concatenated string breaks it.

Not sure how to sign the Assertion using the SIGN api.

Although I am able to sign the concatenated string fine not using KeyVault certificate and instead using the pfx locally by converting the concatenated string to byte[] as it requires under RSA (https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.rsa?view=net-7.0)

I am searching a way to use the Sign API directly without using KeyVaultClient Sign methods (https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.keyvault.keyvaultclientextensions.signasync?view=azure-dotnet)


问:
Use Django ORM in locust
I'm using locust to load test my Django application. I'm currently hardcoding certain values in my locustfile.py:

```<code>GROUP_UUID = "6790f1e6-64f9-4707-aa82-d4edd64c9cc7"

@task
def get_single_group(self):
    self.client.get(f"/api/groups/{GROUP_UUID}/")
</code>```

This obviously fails if GROUP_UUID is not in the database, which occurs whenever I reseed my database so I'm constantly having to change these hardcoded values.

It would be much better if I could dynamically fetch a group at runtime:

```<code>from myapp.models import Group

@task
def get_single_group(self):
    group = Group.objects.first()
    self.client.get(f"/api/groups/{group.id}/")
</code>```

However, I'm getting the following error, which makes sense because locust doesn't know anything about Django:

```<code>ModuleNotFoundError: No module named 'myapp'
</code>```

Is there anyway to use the Django ORM in locustfile.py or do I need to continue hardcoding data all over the place?

Related:

Dynamic GET parameter in locust

Title: Use Django ORM in locust

Body:
I'm using locust to load test my Django application. I'm currently hardcoding certain values in my locustfile.py:

GROUP_UUID = "6790f1e6-64f9-4707-aa82-d4edd64c9cc7"

@task
def get_single_group(self):
    self.client.get(f"/api/groups/{GROUP_UUID}/")

This obviously fails if GROUP_UUID is not in the database, which occurs whenever I reseed my database so I'm constantly having to change these hardcoded values.

It would be much better if I could dynamically fetch a group at runtime:

from myapp.models import Group

@task
def get_single_group(self):
    group = Group.objects.first()
    self.client.get(f"/api/groups/{group.id}/")

However, I'm getting the following error, which makes sense because locust doesn't know anything about Django:

ModuleNotFoundError: No module named 'myapp'

Is there anyway to use the Django ORM in locustfile.py or do I need to continue hardcoding data all over the place?

Related:

Dynamic GET parameter in locust


问:
Send Hubspot form data to 3rd party API upon form submission
I have a customer who wants me to create an integration so contact forms in their customers' Hubspot sites can send data to a 3rd party API. The end user customers have the Marketing Starter package, so they can't use Workflows, as I understand it. The 3rd party API requires a key to be sent in the request header. I'm a career developer and have worked in a variety of environments, but I have very little familiarity with Hubspot. Is what I have described doable? If so, could you point me to some useful resources? Any suggestions and input is appreciated.</p>


问:
Equivalent of Excel RRI Function in Power Query
Is it possible to run functions like the RRI function (or the rate function) in Power Query?  For example, I have a number of columns in Power Query with data:

I would like to create a new column that runs the excel RRI function on these columns and outputs the result in this new column.  Is that possible?  If so, how can I do it?

Here is a link to the RRI and RATE function documentation:

https://support.microsoft.com/en-us/office/rri-function-6f5822d8-7ef1-4233-944c-79e8172930f4

https://support.microsoft.com/en-us/office/rate-function-9f665657-4a7e-4bb7-a030-83fc59e748ce


问:
Message to a user that Application 2 needs to be run first before running Application 1 the second time in Python
I have a main.py and delete.py scripts. After running main.py, before running main.py again, delete.py needs to be run first. Is there a way like a counter that a user will be warned or stopped that after running main.py, delete.py should be executed first before running main.py the next time. So the process would be run main.py then delete.py - main.py then delete.py and so on.

I couldn't find any related issue on the net. Can somebody point me to a solution? Appreciate all your help. Thanks a lot!


问:
What happened to the Spring Security OAuth 2 documentation?
The documentation for Spring Security OAuth2 seems to have completely disappeared.  The github project is moved to the "attic" but the old documentation is nowhere to be found. Anyone know where it is?</p>


问:
Enabling User Provisioning on an Application
I have an Angular application with a C# ASP.NET Core 6 Web API backend.  This application is offered as SAAS and I would like to make it user-provisioning capable by adding some SCIM endpoints.

All the information I can find on how to achieve this seems very complicated and convoluted. I would like to find code examples on how to implement this into my application in a very simple basic way.

Please help.


问:
How to restrict frame ancestors without leaking allowed domains to clients
Currently we list which customers can frame our site with the frame ancestors approach:

Content-Security-Policy: frame-ancestors 'self' https://www.a.org https://www.b.org;;

This leaks information to the client about who our customers are.

Is there a way to implement this restriction without leaking domain names to the client?


问:
mock node-fetch doesn't take the mocked value
Really new to frontend and Typescript unit test

What I am trying to do is mocking a fetch result

Here is my test

```<code>import { renderWithAllProviders } from '../../testUtil/helpers';
import IsItDownBanner from '../IsItDownBanner';

import fetch from 'node-fetch'
jest.mock('node-fetch', ()=>jest.fn())
describe('IsItDownBanner', () => {

  test('renders message when there is is-it-down response', () => {
    const expectedResponse = { name: '', message: 'TEST', level: 1, tickets: '' };
    fetch.mockImplementation(() => Promise.resolve(expectedResponse));

    const { queryByTestId } = renderWithAllProviders(<IsItDownBanner />);
    const description = queryByTestId('isItDownBannerId');
    expect(fetch).toBeCalled;
    expect(description).toBeInTheDocument();
  });
</code>```

I tried to mock the response in the expectedResponse part and assign it to fetch response.

But in test run , i always get null as the output

```<code>    received value must be an HTMLElement or an SVGElement.
    Received has value: null

      13 |     const description = queryByTestId('isItDownBannerId');
      14 |     expect(fetch).toBeCalled;
    > 15 |     expect(description).toBeInTheDocument();
         |                         ^
      16 |   });
      17 |
      18 |   // test('renders the banner when there is override in Succeed is-it-down response', () => {

</code>```

Here is my origin module:

```<code>import React from 'react';

import { IsItDownResponse } from 'components/IsItDownBanner/interface';
import styles from 'components/PageBanner/PageBanner.module.scss';

import { View } from '../../layout';
import { MessageBanner, MessageBannerType } from '../message-banner';

import fetch from 'node-fetch';

const IS_IT_DOWN_URL = '***';
const IS_IT_DOWN_API = `${IS_IT_DOWN_URL}.js`;

const IsItDownBanner = () => {
  const [isItDownResponse, setIsItDownResponse] = React.useState<IsItDownResponse | null>(null);
  fetch(IS_IT_DOWN_API)
      .then((response) => response.json())
      .then((result: IsItDownResponse) => {
        setIsItDownResponse(result);
      });

  let bannerType = MessageBannerType.Error;

  return (
    isItDownResponse && (
      <View className={styles.content}>
        {isItDownResponse === null || isItDownResponse.message === IS_IT_DOWN_GENERAL_MESSAGE ? (
          <></>
        ) : (
          <MessageBanner data-testid="isItDownBannerId" type={bannerType} isDismissible>
            {isItDownResponse.message}
          </MessageBanner>
        )}
      </View>
    )
  );
};
export default IsItDownBanner;
</code>```

After adding

```<code>.catch((error: any) => {
        console.error(error);
      });
</code>```

to fetch part, i got error log

```<code>FetchError {
      message: 'invalid json response body at  reason: Unexpected end of JSON input',
      type: 'invalid-json'
    }
</code>```

I feel like i don't mock the fetch successfully in test file and when i render the page, it is still calling the real api (which should not work in local test).

Body:
Really new to frontend and Typescript unit test

What I am trying to do is mocking a fetch result

Here is my test

import { renderWithAllProviders } from '../../testUtil/helpers';
import IsItDownBanner from '../IsItDownBanner';

import fetch from 'node-fetch'
jest.mock('node-fetch', ()=>jest.fn())
describe('IsItDownBanner', () => {

  test('renders message when there is is-it-down response', () => {
    const expectedResponse = { name: '', message: 'TEST', level: 1, tickets: '' };
    fetch.mockImplementation(() => Promise.resolve(expectedResponse));

    const { queryByTestId } = renderWithAllProviders(<IsItDownBanner />);
    const description = queryByTestId('isItDownBannerId');
    expect(fetch).toBeCalled;
    expect(description).toBeInTheDocument();
  });

I tried to mock the response in the expectedResponse part and assign it to fetch response.

But in test run , i always get null as the output

    received value must be an HTMLElement or an SVGElement.
    Received has value: null

      13 |     const description = queryByTestId('isItDownBannerId');
      14 |     expect(fetch).toBeCalled;
    > 15 |     expect(description).toBeInTheDocument();
         |                         ^
      16 |   });
      17 |
      18 |   // test('renders the banner when there is override in Succeed is-it-down response', () => {

Here is my origin module:

import React from 'react';

import { IsItDownResponse } from 'components/IsItDownBanner/interface';
import styles from 'components/PageBanner/PageBanner.module.scss';

import { View } from '../../layout';
import { MessageBanner, MessageBannerType } from '../message-banner';

import fetch from 'node-fetch';

const IS_IT_DOWN_URL = '***';
const IS_IT_DOWN_API = `${IS_IT_DOWN_URL}.js`;

const IsItDownBanner = () => {
  const [isItDownResponse, setIsItDownResponse] = React.useState<IsItDownResponse | null>(null);
  fetch(IS_IT_DOWN_API)
      .then((response) => response.json())
      .then((result: IsItDownResponse) => {
        setIsItDownResponse(result);
      });

  let bannerType = MessageBannerType.Error;

  return (
    isItDownResponse && (
      <View className={styles.content}>
        {isItDownResponse === null || isItDownResponse.message === IS_IT_DOWN_GENERAL_MESSAGE ? (
          <></>
        ) : (
          <MessageBanner data-testid="isItDownBannerId" type={bannerType} isDismissible>
            {isItDownResponse.message}
          </MessageBanner>
        )}
      </View>
    )
  );
};
export default IsItDownBanner;

After adding

.catch((error: any) => {
        console.error(error);
      });

to fetch part, i got error log

FetchError {
      message: 'invalid json response body at  reason: Unexpected end of JSON input',
      type: 'invalid-json'
    }

I feel like i don't mock the fetch successfully in test file and when i render the page, it is still calling the real api (which should not work in local test).


问:
How do I list all users using react-redux-firebase at one time?
I'm facing weird issue while trying to list all users at one time in React.
I tried to fetch all users from firestore. Unlike the collections that are fetched at once, the users collection is not fetched at once.

I think firebase integration is not correct so attached my index.js file.

```<code>...
// react-redux-firebase config
const rrfConfig = {
  userProfile: "users", // where profiles are stored in database
  useFirestoreForProfile: true,
  presence: "presence", // where list of online users is stored in database
  sessions: "sessions", // where list of user sessions is stored in database (presence must be enabled)
};

const initialState = {};
const middleware = [thunk.withExtraArgument({ getFirebase, getFirestore })];

const store = createStore(
  rootReducer,
  initialState,
  compose(applyMiddleware(...middleware))
);

const rrfProps = {
  firebase,
  config: rrfConfig,
  dispatch: store.dispatch,
  createFirestoreInstance, // <- needed if using firestore
};

const container = document.getElementById("app");

function App() {
  return (
    <Provider store={store}>
      <React.StrictMode>
        <ReactReduxFirebaseProvider {...rrfProps}>
          <Routers />
        </ReactReduxFirebaseProvider>
      </React.StrictMode>
    </Provider>
  );
}

ReactDOM.render(<App />, container);

reportWebVitals();
</code>```

Here is my package versions.

```<code>"react": "^17.0.2",
"react-redux": "^8.0.5",
"react-redux-firebase": "^3.11.0",
"redux": "^4.2.0",
"redux-firestore": "^1.0.0",
"redux-thunk": "^2.4.2",
</code>```

Body:
I'm facing weird issue while trying to list all users at one time in React.
I tried to fetch all users from firestore. Unlike the collections that are fetched at once, the users collection is not fetched at once.

I think firebase integration is not correct so attached my index.js file.

...
// react-redux-firebase config
const rrfConfig = {
  userProfile: "users", // where profiles are stored in database
  useFirestoreForProfile: true,
  presence: "presence", // where list of online users is stored in database
  sessions: "sessions", // where list of user sessions is stored in database (presence must be enabled)
};

const initialState = {};
const middleware = [thunk.withExtraArgument({ getFirebase, getFirestore })];

const store = createStore(
  rootReducer,
  initialState,
  compose(applyMiddleware(...middleware))
);

const rrfProps = {
  firebase,
  config: rrfConfig,
  dispatch: store.dispatch,
  createFirestoreInstance, // <- needed if using firestore
};

const container = document.getElementById("app");

function App() {
  return (
    <Provider store={store}>
      <React.StrictMode>
        <ReactReduxFirebaseProvider {...rrfProps}>
          <Routers />
        </ReactReduxFirebaseProvider>
      </React.StrictMode>
    </Provider>
  );
}

ReactDOM.render(<App />, container);

reportWebVitals();

Here is my package versions.

"react": "^17.0.2",
"react-redux": "^8.0.5",
"react-redux-firebase": "^3.11.0",
"redux": "^4.2.0",
"redux-firestore": "^1.0.0",
"redux-thunk": "^2.4.2",


问:
Live Activities with UIKit?
I have an app that uses UIKit, and I'd like to add Live Activites support to it. I started a new project that makes full use of SwiftUI. It has Live Activities that work perfectly, and all of the functions work properly.

However...

When I launch my app in UIKit, I generate a new SwiftUI File and a new Widget Target. I copied the exact codes into my app and was able to open a SwiftUI view with the UIHostingController. No problem, but when I press the "Run Live Activities" button, I see a white border on Dynamic Island but nothing else. There are no Live Activites displayed on the lock screen. I've already added Support Live Activities to the list and set it to YES. What did I overlook?

Title: Live Activities with UIKit?