问:
Every version of integration_test depends on flutter_driver any from sdk which depends on crypto 2.1.5
I've been getting an error ever since I tried adding integration_test package along with get_test and it's primarily due to the fact that just_audio depends on crypto: ^3.0.0 while integration_test depends on crypto: ^2.1.5.

I tried to look online to see if it's possible to only install dependencies without dev_dependencies however it seems like flutter pub cli tool doesn't support that yet based on this issue.

Here is my pubspec.yaml

environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^1.0.2
  share: ^2.0.1
  get:
  get_storage:
  shared_preferences: ^2.0.5
  audio_service: 0.17.0-nullsafety.0
  just_audio: ^0.7.4

dev_dependencies:
  flutter_test:
    sdk: flutter

  get_test: ^3.13.3
  integration_test: ^1.0.2+1
  test: ^1.14.4
```
<p>This is the error I am getting.</p>
```Because every version of integration_test depends on flutter_driver any from sdk which depends on crypto 2.1.5, every version of integration_test requires crypto 2.1.5.
And because just_audio 0.7.4 depends on crypto ^3.0.0 and no versions of just_audio match >0.7.4 <0.8.0, integration_test is incompatible with just_audio ^0.7.4.
So, because egy_fm_radio depends on both just_audio ^0.7.4 and integration_test ^1.0.2+1, version solving failed.
pub get failed (1; So, because egy_fm_radio depends on both just_audio ^0.7.4 and integration_test ^1.0.2+1, version solving failed.)
```

答:
Looking through your pubspec.yaml it appears the problem lies within the crypto dependency mismatch.

Inside your pubspec.yaml  you can explictly declare the latest crypto version:

environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^1.0.2
  share: ^2.0.1
  crypto: 3.0.1
  get:
  get_storage:
  shared_preferences: ^2.0.5
  audio_service: 0.17.0-nullsafety.0
  just_audio: ^0.7.4

dev_dependencies:
  flutter_test:
    sdk: flutter

  get_test: ^3.13.3
  integration_test: ^1.0.2+1
  test: ^1.14.4
```

What happens is that when you use so many packages, some of those packages use some other packages. It may so happen that two or more packages use the same package.So, it creates an error incase of mismatch because you cannot have two different versions of the same package.

Body:
I've been getting an error ever since I tried adding integration_test package along with get_test and it's primarily due to the fact that just_audio depends on crypto: ^3.0.0 while integration_test depends on crypto: ^2.1.5.

I tried to look online to see if it's possible to only install dependencies without dev_dependencies however it seems like flutter pub cli tool doesn't support that yet based on this issue.

Here is my pubspec.yaml

environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^1.0.2
  share: ^2.0.1
  get:
  get_storage:
  shared_preferences: ^2.0.5
  audio_service: 0.17.0-nullsafety.0
  just_audio: ^0.7.4

dev_dependencies:
  flutter_test:
    sdk: flutter

  get_test: ^3.13.3
  integration_test: ^1.0.2+1
  test: ^1.14.4

This is the error I am getting.

Because every version of integration_test depends on flutter_driver any from sdk which depends on crypto 2.1.5, every version of integration_test requires crypto 2.1.5.
And because just_audio 0.7.4 depends on crypto ^3.0.0 and no versions of just_audio match >0.7.4 <0.8.0, integration_test is incompatible with just_audio ^0.7.4.
So, because egy_fm_radio depends on both just_audio ^0.7.4 and integration_test ^1.0.2+1, version solving failed.
pub get failed (1; So, because egy_fm_radio depends on both just_audio ^0.7.4 and integration_test ^1.0.2+1, version solving failed.)

Body:
Looking through your pubspec.yaml it appears the problem lies within the crypto dependency mismatch.

Inside your pubspec.yaml  you can explictly declare the latest crypto version:

environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^1.0.2
  share: ^2.0.1
  crypto: 3.0.1
  get:
  get_storage:
  shared_preferences: ^2.0.5
  audio_service: 0.17.0-nullsafety.0
  just_audio: ^0.7.4

dev_dependencies:
  flutter_test:
    sdk: flutter

  get_test: ^3.13.3
  integration_test: ^1.0.2+1
  test: ^1.14.4

What happens is that when you use so many packages, some of those packages use some other packages. It may so happen that two or more packages use the same package.So, it creates an error incase of mismatch because you cannot have two different versions of the same package.


来源: stackexchange

问:
Trying to change logo that is displayed in this PHP popup form
Want to start off by saying I am not proficient in PHP at all so I apologise if my terminology and understanding is very poor.

I'm using Wordpress with a theme called Kicker. With this theme, when a user tries to login/signup to my website they are presented with a pop-up form. This pop-up form is showing my main logo, which is white, and is showing it on the white background. I'm wanting to change the logo to the alternate one which is dark but I am very unsure how to.

The file I found is called 'tpl.login-popup.php' and I have found the part of code which calls for the template where this image is located:

```<code><?php
                    // Logo
                    get_template_part( apply_filters( 'kicker_filter_get_template_part', 'templates/header-logo' ) );
                    ?>
</code>```

Now from what I understand, this is trying to get the logo from 'templates/header-logo' and here is the contents of that PHP file called 'header-logo.php:

```<code><?php
/**
 * The template to display the logo or the site name and the slogan in the Header
 *
 * @package KICKER
 * @since KICKER 1.0
 */

$kicker_args = get_query_var( 'kicker_logo_args' );

// Site logo
$kicker_logo_type   = isset( $kicker_args['type'] ) ? $kicker_args['type'] : '';
$kicker_logo_image  = kicker_get_logo_image( $kicker_logo_type );
$kicker_logo_text   = kicker_is_on( kicker_get_theme_option( 'logo_text' ) ) ? get_bloginfo( 'name' ) : '';
$kicker_logo_slogan = get_bloginfo( 'description', 'display' );
if ( ! empty( $kicker_logo_image['logo'] ) || ! empty( $kicker_logo_text ) ) {
    ?><a class="sc_layouts_logo" href="<?php echo esc_url( home_url( '/' ) ); ?>">
        <?php
        if ( ! empty( $kicker_logo_image['logo'] ) ) {
            if ( empty( $kicker_logo_type ) && function_exists( 'the_custom_logo' ) && is_numeric( $kicker_logo_image['logo'] ) && $kicker_logo_image['logo'] > 0 ) {
                the_custom_logo();
            } else {
                $kicker_attr = kicker_getimagesize( $kicker_logo_image['logo'] );
                echo '<img src="' . esc_url( $kicker_logo_image['logo'] ) . '"'
                        . ( ! empty( $kicker_logo_image['logo_retina'] ) ? ' srcset="' . esc_url( $kicker_logo_image['logo_retina'] ) . ' 2x"' : '' )
                        . ' alt="' . esc_attr( $kicker_logo_text ) . '"'
                        . ( ! empty( $kicker_attr[3] ) ? ' ' . wp_kses_data( $kicker_attr[3] ) : '' )
                        . '>';
            }
        } else {
            kicker_show_layout( kicker_prepare_macros( $kicker_logo_text ), '<span class="logo_text">', '</span>' );
            kicker_show_layout( kicker_prepare_macros( $kicker_logo_slogan ), '<span class="logo_slogan">', '</span>' );
        }
        ?>
    </a>
    <?php
}
</code>```

I'm wondering if there's an easy way I can edit something to allow the 'tpl.login-popup.php' file to request the other image? I was thinking I could try and edit the header-logo.php file but then I am worried it would affect other parts of the website.

I'm sorry if this doesn't make sense, but I thought I would try and ask. Please let me know if I can provide more information.

Thank you.

答:
Without seeing all the code it is difficult to see if modifying these files would affect other spots of your site.

Your "header-logo.php" file is checking to see if you uploaded a custom logo and setting the values to display the logo, alt tag and description. If you are able to find where you upload your logo you could swap it there (but it would be for all logo uses in your site).

If you want the logo changed only in this specific location, you could simply hard code the image of choice as follows:

```<code><?php
// Logo

// add slashes in front of next line to comment out original logo
// get_template_part( apply_filters( 'kicker_filter_get_template_part', 'templates/header-logo' ) );
?>

<img src="YOUR_LOGO_ADDRESS_HERE" alt="ALT TEXT OF YOUR IMAGE" width="ENTER_DESIRED_WIDTH" height="ENTER_DESIRED_HEIGHT" />
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Want to start off by saying I am not proficient in PHP at all so I apologise if my terminology and understanding is very poor.

I'm using Wordpress with a theme called Kicker. With this theme, when a user tries to login/signup to my website they are presented with a pop-up form. This pop-up form is showing my main logo, which is white, and is showing it on the white background. I'm wanting to change the logo to the alternate one which is dark but I am very unsure how to.

The file I found is called 'tpl.login-popup.php' and I have found the part of code which calls for the template where this image is located:

<?php
                    // Logo
                    get_template_part( apply_filters( 'kicker_filter_get_template_part', 'templates/header-logo' ) );
                    ?>

Now from what I understand, this is trying to get the logo from 'templates/header-logo' and here is the contents of that PHP file called 'header-logo.php:

<?php
/**
 * The template to display the logo or the site name and the slogan in the Header
 *
 * @package KICKER
 * @since KICKER 1.0
 */

$kicker_args = get_query_var( 'kicker_logo_args' );

// Site logo
$kicker_logo_type   = isset( $kicker_args['type'] ) ? $kicker_args['type'] : '';
$kicker_logo_image  = kicker_get_logo_image( $kicker_logo_type );
$kicker_logo_text   = kicker_is_on( kicker_get_theme_option( 'logo_text' ) ) ? get_bloginfo( 'name' ) : '';
$kicker_logo_slogan = get_bloginfo( 'description', 'display' );
if ( ! empty( $kicker_logo_image['logo'] ) || ! empty( $kicker_logo_text ) ) {
    ?><a class="sc_layouts_logo" href="<?php echo esc_url( home_url( '/' ) ); ?>">
        <?php
        if ( ! empty( $kicker_logo_image['logo'] ) ) {
            if ( empty( $kicker_logo_type ) && function_exists( 'the_custom_logo' ) && is_numeric( $kicker_logo_image['logo'] ) && $kicker_logo_image['logo'] > 0 ) {
                the_custom_logo();
            } else {
                $kicker_attr = kicker_getimagesize( $kicker_logo_image['logo'] );
                echo '';
            }
        } else {
            kicker_show_layout( kicker_prepare_macros( $kicker_logo_text ), '', '' );
            kicker_show_layout( kicker_prepare_macros( $kicker_logo_slogan ), '', '' );
        }
        ?>

    <?php
}

I'm wondering if there's an easy way I can edit something to allow the 'tpl.login-popup.php' file to request the other image? I was thinking I could try and edit the header-logo.php file but then I am worried it would affect other parts of the website.

I'm sorry if this doesn't make sense, but I thought I would try and ask. Please let me know if I can provide more information.

Thank you.

Body:
Without seeing all the code it is difficult to see if modifying these files would affect other spots of your site.

Your "header-logo.php" file is checking to see if you uploaded a custom logo and setting the values to display the logo, alt tag and description. If you are able to find where you upload your logo you could swap it there (but it would be for all logo uses in your site).

If you want the logo changed only in this specific location, you could simply hard code the image of choice as follows:

<?php
// Logo

// add slashes in front of next line to comment out original logo
// get_template_part( apply_filters( 'kicker_filter_get_template_part', 'templates/header-logo' ) );
?>

<img src="YOUR_LOGO_ADDRESS_HERE" alt="ALT TEXT OF YOUR IMAGE" width="ENTER_DESIRED_WIDTH" height="ENTER_DESIRED_HEIGHT" />


问:
Why Are My Unit Tests Inconsistently Passing/Failing? (Golang and ScyllaDB)
I'm running into issue with unit tests pertaining to ScyllaDB in Golang. The code doesn't seem to be the problem. The unit tests will sometimes work perfectly, but just as often will also fail. This leads me to believe this could be a database issue, but I'm not sure what it could be. For example, I get back errors like this after creating a new entity test_server with some basic entity metadata description: "desc", owner: "owner":

```<code>Error Trace:    test_file.go:243
                                            test_file.go:68
                Error:          Not equal:
                                expected: &model.EntityMetadata{state:impl.MessageState{NoUnkeyedLiterals:pragma.NoUnkeyedLiterals{}, DoNotCompare:pragma.DoNotCompare{}, DoNotCopy:pragma.DoNotCopy{}, atomicMessageInfo:(*impl.MessageInfo)(nil)}, sizeCache:0, unknownFields:[]uint8(nil), EntityType:(*string)(0xc000512420), Description:(*string)(0xc000512430), Owner:(*string)(0xc000512440), Features:[]*model.FeatureMetadata(nil), DefaultTtl:(*int64)(0xc00003d1a8)}
                                actual  : &model.EntityMetadata{state:impl.MessageState{NoUnkeyedLiterals:pragma.NoUnkeyedLiterals{}, DoNotCompare:pragma.DoNotCompare{}, DoNotCopy:pragma.DoNotCopy{}, atomicMessageInfo:(*impl.MessageInfo)(nil)}, sizeCache:0, unknownFields:[]uint8(nil), EntityType:(*string)(0xc0005122d0), Description:(*string)(0xc0005122e0), Owner:(*string)(0xc0005122f0), Features:[]*model.FeatureMetadata(nil), DefaultTtl:(*int64)(0xc00003d170)}

                                Diff:
                                --- Expected
                                +++ Actual
                                @@ -13,4 +13,4 @@
                                  EntityType: (*string)((len=11) "test_server"),
                                - Description: (*string)((len=4) "desc"),
                                - Owner: (*string)((len=5) "owner"),
                                + Description: (*string)(""),
                                + Owner: (*string)(""),
                                  Features: ([]*model.FeatureMetadata) <nil>,
                Test:           TestServer/GetEntityList
</code>```

Of course the actual results should appear like this (which I do get sometime):

```<code>                                    --- Expected
                                    +++ Actual
                                    @@ -13,4 +13,4 @@
                                      EntityType: (*string)((len=11) "test_server"),
                                    - Description: (*string)((len=4) "desc"),
                                    - Owner: (*string)((len=5) "owner"),
                                    + Description: (*string)("desc"),
                                    + Owner: (*string)("owner"),
                                      Features: ([]*model.FeatureMetadata) <nil>,
                    Test:           TestServer/GetEntityList
</code>```

Here is what the unit test looks like (line 68 is where the unit test was called from, a function, and line 243 is where the function lies in the test_file.go lies). Assume that a function earlier has already attempted created this table, with the description and owner:

```<code>func getEntity(t *testing.T, ctx context.Context, s *Server) {
   res, err := s.GetEntity(ctx, &models.EntityRequest{})
   if assert.NoError(t, err) {
      expected := &models.EntityMetadata{
         EntityType: proto.String("test_server"),
         Description: proto.String("desc"),
         Owner: proto.String("owner"),
   }
   assert.Equal(t, expected, entity)
}
</code>```

I get errors/inconsistencies like these in other unit tests as well, this was just one of them provided. Any help would be appreciated, I've been trying to debug this for a while now.
Note: I have an established Read/Write connection for these unit tests, the database is not mocked.

答:
Without knowing the test code, my assumption might be wrong, but:
it seems as you are comparing not the data but pointers to data in some cases (at least the output suggests this):

```<code>EntityType:(*string)(0xc000512420), Description:(*string)(0xc000512430), Owner:(*string)(0xc000512440),
</code>```

Actual:

```<code>EntityType:(*string)(0xc0005122d0), Description:(*string)(0xc0005122e0),Owner:(*string)(0xc0005122f0)
</code>```

This does not work most of the time; you should compare the actual data values.

Body:
I'm running into issue with unit tests pertaining to ScyllaDB in Golang. The code doesn't seem to be the problem. The unit tests will sometimes work perfectly, but just as often will also fail. This leads me to believe this could be a database issue, but I'm not sure what it could be. For example, I get back errors like this after creating a new entity test_server with some basic entity metadata description: "desc", owner: "owner":

Error Trace:    test_file.go:243
                                            test_file.go:68
                Error:          Not equal:
                                expected: &model.EntityMetadata{state:impl.MessageState{NoUnkeyedLiterals:pragma.NoUnkeyedLiterals{}, DoNotCompare:pragma.DoNotCompare{}, DoNotCopy:pragma.DoNotCopy{}, atomicMessageInfo:(*impl.MessageInfo)(nil)}, sizeCache:0, unknownFields:[]uint8(nil), EntityType:(*string)(0xc000512420), Description:(*string)(0xc000512430), Owner:(*string)(0xc000512440), Features:[]*model.FeatureMetadata(nil), DefaultTtl:(*int64)(0xc00003d1a8)}
                                actual  : &model.EntityMetadata{state:impl.MessageState{NoUnkeyedLiterals:pragma.NoUnkeyedLiterals{}, DoNotCompare:pragma.DoNotCompare{}, DoNotCopy:pragma.DoNotCopy{}, atomicMessageInfo:(*impl.MessageInfo)(nil)}, sizeCache:0, unknownFields:[]uint8(nil), EntityType:(*string)(0xc0005122d0), Description:(*string)(0xc0005122e0), Owner:(*string)(0xc0005122f0), Features:[]*model.FeatureMetadata(nil), DefaultTtl:(*int64)(0xc00003d170)}

                                Diff:
                                --- Expected
                                +++ Actual
                                @@ -13,4 +13,4 @@
                                  EntityType: (*string)((len=11) "test_server"),
                                - Description: (*string)((len=4) "desc"),
                                - Owner: (*string)((len=5) "owner"),
                                + Description: (*string)(""),
                                + Owner: (*string)(""),
                                  Features: ([]*model.FeatureMetadata) <nil>,
                Test:           TestServer/GetEntityList

Of course the actual results should appear like this (which I do get sometime):

                                    --- Expected
                                    +++ Actual
                                    @@ -13,4 +13,4 @@
                                      EntityType: (*string)((len=11) "test_server"),
                                    - Description: (*string)((len=4) "desc"),
                                    - Owner: (*string)((len=5) "owner"),
                                    + Description: (*string)("desc"),
                                    + Owner: (*string)("owner"),
                                      Features: ([]*model.FeatureMetadata) <nil>,
                    Test:           TestServer/GetEntityList

Here is what the unit test looks like (line 68 is where the unit test was called from, a function, and line 243 is where the function lies in the test_file.go lies). Assume that a function earlier has already attempted created this table, with the description and owner:

func getEntity(t *testing.T, ctx context.Context, s *Server) {
   res, err := s.GetEntity(ctx, &models.EntityRequest{})
   if assert.NoError(t, err) {
      expected := &models.EntityMetadata{
         EntityType: proto.String("test_server"),
         Description: proto.String("desc"),
         Owner: proto.String("owner"),
   }
   assert.Equal(t, expected, entity)
}

I get errors/inconsistencies like these in other unit tests as well, this was just one of them provided. Any help would be appreciated, I've been trying to debug this for a while now.
Note: I have an established Read/Write connection for these unit tests, the database is not mocked.

Body:
Without knowing the test code, my assumption might be wrong, but:
it seems as you are comparing not the data but pointers to data in some cases (at least the output suggests this):

EntityType:(*string)(0xc000512420), Description:(*string)(0xc000512430), Owner:(*string)(0xc000512440),

Actual:

EntityType:(*string)(0xc0005122d0), Description:(*string)(0xc0005122e0),Owner:(*string)(0xc0005122f0)

This does not work most of the time; you should compare the actual data values.


问:
Color area beneath sympy function plot
I have a sympy function, I want to plot it and color the area beneath the curve, how can I do it?

Code

```<code>import sympy as sy

x = sy.symbols('x')
f = sy.sin(x)

sy.plot(f, (x, 0, sy.pi))
</code>```

Plot

答:
i have created the same output without using matplotlib directly(sympy already uses sympy)

```<code>import sympy as sy
import numpy as np
from sympy.plotting import plot
x = sy.symbols('x')
f = sy.sin(x)
x_array = np.linspace(0, np.pi, 1000)
f_array = sy.lambdify(x, f)(x_array)
plot(f, (x, 0, sy.pi), fill={'x': x_array,'y1':f_array,'color':'green'})
</code>```

i got the output

Title: Color area beneath sympy function plot

Body:
I have a sympy function, I want to plot it and color the area beneath the curve, how can I do it?

Code

import sympy as sy

x = sy.symbols('x')
f = sy.sin(x)

sy.plot(f, (x, 0, sy.pi))

Plot

Body:
i have created the same output without using matplotlib directly(sympy already uses sympy)

import sympy as sy
import numpy as np
from sympy.plotting import plot
x = sy.symbols('x')
f = sy.sin(x)
x_array = np.linspace(0, np.pi, 1000)
f_array = sy.lambdify(x, f)(x_array)
plot(f, (x, 0, sy.pi), fill={'x': x_array,'y1':f_array,'color':'green'})

i got the output


问:
How can spaces be removed in HTML output?
Here's my HTML code in a markdown editor:

```<code><div>

This is some text

<emb>Reference:<emb>
    <ol>
        <li><i>Reference link #1</i></li>
        <li><i>Reference link #2</i></li>
    </ol>
</div>

This is some text.

<style>
  emb {
       font-weight: 500;
       background: transparent;
       font-size: 18px
    }
</style>
</code>```

It produces result as below:

What causes this space?

答:
Margins of elements. You can use CSS to remove them like this:

```<code><p style="margin-bottom: 0;"> <emb> Reference: </emb> </p>
</code>```

and on ol

```<code><ol style="margin-top: 0;">
</code>```

I had to remove both margins on
 and on
 to remove the space

You can also use inspect element on browsers to see the answer.

Body:
Here's my HTML code in a markdown editor:

This is some text

<emb>Reference:<emb>

Reference link #1

Reference link #2

This is some text.

It produces result as below:

What causes this space?

Body:
Margins of elements. You can use CSS to remove them like this:

<p style="margin-bottom: 0;"> <emb> Reference: </emb> </p>

and on ol

<ol style="margin-top: 0;">

I had to remove both margins on <p> and on <ol> to remove the space

You can also use inspect element on browsers to see the answer.


问:
Web3js event listen / subscribe to transactions to or from a wallet address
So I am connecting to Binance Smart Chain RPC websocket from Moralis.io. And trying to listen to wallet amount changes of a certain wallet address.

What I want to do is, I want to trigger a event whenever there is a transfer from or to this wallet address. I understand how to do it with BEP20 tokens but I require a solution to monitor the wallet address for BNB transfers.

The code that I put together:

```<code>const web3 = new Web3(new Web3.providers.WebsocketProvider('URI'))

let options = {
address: '0xe....'
}

const subscribe = web3.eth.subscribe('logs', options, (err, res) => {})

subscribe.on('data', (txLog) => console.log(txLog))

</code>```

This doesn't work when I send a certain amount of BNB to this account.

I went through the documentation of web3js but couldn't figure out.

I found a longer way around for this problem where someone suggests to listen to all pending transactions and try to get the transaction data of each of these transactions and evaluate if any of these are from or to the wallet address. But I think it is an extremely ineffective and inefficient way to do it as it requires someone to run their own node to do it in a meaningful way.

答:
listen to all pending transactions and try to get the transaction data of each of these transactions

I agree that this is an ineffective way. But with the current state of the JSON-RPC API, it's still the most effective way available. Apart from using a 3rd party service that does all this work in the background and provides the data over their custom API.

Note: The link goes to Ethereum documentation, but Binance Smart Chain implements the same JSON-RPC API.

There's simply no method to subscribe to or poll incoming native transactions to a specified address.

And since web3, ethers.js, and many other libraries are wrappers of this API, they can only support methods that the API supports.

Body:
So I am connecting to Binance Smart Chain RPC websocket from Moralis.io. And trying to listen to wallet amount changes of a certain wallet address.

What I want to do is, I want to trigger a event whenever there is a transfer from or to this wallet address. I understand how to do it with BEP20 tokens but I require a solution to monitor the wallet address for BNB transfers.

The code that I put together:

const web3 = new Web3(new Web3.providers.WebsocketProvider('URI'))

let options = {
address: '0xe....'
}

const subscribe = web3.eth.subscribe('logs', options, (err, res) => {})

subscribe.on('data', (txLog) => console.log(txLog))

This doesn't work when I send a certain amount of BNB to this account.

I went through the documentation of web3js but couldn't figure out.

I found a longer way around for this problem where someone suggests to listen to all pending transactions and try to get the transaction data of each of these transactions and evaluate if any of these are from or to the wallet address. But I think it is an extremely ineffective and inefficient way to do it as it requires someone to run their own node to do it in a meaningful way.


问:
How can I fill a column with values that are computed between two dates in pandas, with a delay of one row, if I have repeating dates?
I have this dataframe:

Date
Position
TrainerID

2017-09-03
4
1788

2017-09-16
5
1788

2017-10-14
1
1788

2017-10-14
3
1788

I want to compute on every row the winning percentage so far for the races in the last 1000 days, for a certain TrainerID. The result will be stored in a Win% Column. Dates need not to be unique. However, the winning % is considered to be before the race happened, so the current row is excluded. Thus, the results are delayed by one row.

So, what I am looking for is a result like this:

Date
Position
TrainerID
Win%

2017-09-03
4
1788
0 (0 wins, 0 races)

2017-09-16
5
1788
0 (0 wins, 1 races)

2017-10-14
1
1788
0 (0 wins, 2 races)

2017-10-14
3
1788
33 (1 win, 3 races)

I have most of the problem solved. I know I should add a shift(1) to the code, but I am not sure where it should go. My last attempt was:

```<code>df['Win'] = df['Position'].eq(1)
df = (df.reset_index().groupby('TrainerID').shift(1).apply(
            lambda x: x.rolling(no_days, on='Date').agg(
                {'Win': 'mean', 'index': 'max'}).reset_index(drop=True).set_index('index').shift().mul(100).round(2)))
</code>```

But I got the following error message:

invalid on specified as Date, must be a column (of DataFrame), an Index or None

So, where do I put the shift() function? How can I solve this?

答:
You could use rolling with the Date index a datetime:

```<code>df['Date'] = pd.to_datetime(df['Date'])
df['Win%'] = (
 df.set_index('Date')
   .rolling('1000d')  # last 1000 days
   ['Position']
   .apply(lambda s: round(s.eq(1).sum()/len(s)*100))
   .shift()
   .values
)
</code>```

output:

```<code>        Date  Position  TrainerID  Win%
0 2017-09-03         4       1788   NaN
1 2017-09-16         5       1788   0.0
2 2017-10-14         1       1788   0.0
3 2017-10-14         3       1788  33.0
</code>```

NB. it is not clear if there are several "TrainerID", but in this case you could also perform everything grouped by "TrainerID"

applying per group

```<code>df['Win%'] = (
 df.set_index('Date')
   .groupby('TrainerID')
   .rolling('1000d')['Position']
   .apply(lambda s: round(s.eq(1).sum()/len(s)*100))
   .groupby('TrainerID').shift()
   .values
)
</code>```

output:

```<code>        Date  Position  TrainerID  Win%
0 2017-09-03         4       1788   NaN
1 2017-09-16         5       1788   0.0
2 2017-10-14         1       1788   0.0
3 2017-10-14         3       1788  33.0
4 2017-09-03         4       1789   NaN
5 2017-09-16         5       1789   0.0
6 2017-10-14         1       1789   0.0
7 2017-10-14         3       1789  33.0
</code>```

Body:
I have this dataframe:

Date
Position
TrainerID

2017-09-03
4
1788

2017-09-16
5
1788

2017-10-14
1
1788

2017-10-14
3
1788

I want to compute on every row the winning percentage so far for the races in the last 1000 days, for a certain TrainerID. The result will be stored in a Win% Column. Dates need not to be unique. However, the winning % is considered to be before the race happened, so the current row is excluded. Thus, the results are delayed by one row.

So, what I am looking for is a result like this:

Date
Position
TrainerID
Win%

2017-09-03
4
1788
0 (0 wins, 0 races)

2017-09-16
5
1788
0 (0 wins, 1 races)

2017-10-14
1
1788
0 (0 wins, 2 races)

2017-10-14
3
1788
33 (1 win, 3 races)

I have most of the problem solved. I know I should add a shift(1) to the code, but I am not sure where it should go. My last attempt was:

df['Win'] = df['Position'].eq(1)
df = (df.reset_index().groupby('TrainerID').shift(1).apply(
            lambda x: x.rolling(no_days, on='Date').agg(
                {'Win': 'mean', 'index': 'max'}).reset_index(drop=True).set_index('index').shift().mul(100).round(2)))

But I got the following error message:

invalid on specified as Date, must be a column (of DataFrame), an Index or None

So, where do I put the shift() function? How can I solve this?

Body:
You could use rolling with the Date index a datetime:

df['Date'] = pd.to_datetime(df['Date'])
df['Win%'] = (
 df.set_index('Date')
   .rolling('1000d')  # last 1000 days
   ['Position']
   .apply(lambda s: round(s.eq(1).sum()/len(s)*100))
   .shift()
   .values
)

output:

        Date  Position  TrainerID  Win%
0 2017-09-03         4       1788   NaN
1 2017-09-16         5       1788   0.0
2 2017-10-14         1       1788   0.0
3 2017-10-14         3       1788  33.0

NB. it is not clear if there are several "TrainerID", but in this case you could also perform everything grouped by "TrainerID"

applying per group

df['Win%'] = (
 df.set_index('Date')
   .groupby('TrainerID')
   .rolling('1000d')['Position']
   .apply(lambda s: round(s.eq(1).sum()/len(s)*100))
   .groupby('TrainerID').shift()
   .values
)

output:

        Date  Position  TrainerID  Win%
0 2017-09-03         4       1788   NaN
1 2017-09-16         5       1788   0.0
2 2017-10-14         1       1788   0.0
3 2017-10-14         3       1788  33.0
4 2017-09-03         4       1789   NaN
5 2017-09-16         5       1789   0.0
6 2017-10-14         1       1789   0.0
7 2017-10-14         3       1789  33.0


问:
Why does vs code show so many untracked files whenever I try to see the code for a built-in flutter widget?
While working in Flutter, sometimes I wish to see how a certain built-in or third-party widget works internally. And when I do ctrl+click on my vs code on that widget and hope to see its code, vs code then suddenly shows me like 140-150 untracked files. It only happens when I try to view the code for built-in or third-party widgets.
Help me!!!!
Thanks...

答: You can right click on the flutter repo (the one above the git commit message text field) and close repository.


问:
Game not printing or updating when AI is thinking
I have a game I am developing in Unity where AI is doing large calculations when it is its turn. It searches the position to depth 1, then 2, then 3 etc. Between each depth I want to instantiate a Gameobject with info about the depth to UI. The problem is that nothing happens until the AI is completely finished, then all items are added at once. Here is some code to explain better:

```<code>private void AIMakeMove()
{
    for (int currentDepth = 1; currentDepth < maxDepth + 1; currentDepth++)
    {
        SearchPosition(currentDepth);
    }
}

private void SearchPosition(int _currentDepth)
{
    // Search the position to the given depth
    score = Negamax(_currentDepth);

     // Print things   PROBLEM HERE
    GameObject printItem = Instantiate(printItemPrefab, printItemParent.transform);
    Debug.Log(_currentDepth);
}
</code>```

I also tried just a simple Debug.Log instead of Instantiate but same thing happens then, all prints to console happens after the AI is done with its thinking process.

Why is my UI not updating with information? I tell it to create some things after it run the first iteration with depth 0 but it skips this step and goes on depth 2 instead. Can someone please let me know how to get information out between each depth?

答:
Try using a thread:</p>
```<code>private void AIMakeMove()
    {
        new System.Threading.Thread(() =>
        {
            for (int currentDepth = 1; currentDepth < maxDepth + 1; currentDepth++)
            {
                SearchPosition(currentDepth);
            }
        }).Start();
    }

    private void SearchPosition(int _currentDepth)
    {
        // Search the position to the given depth
        score = Negamax(_currentDepth);

        // Print things   PROBLEM HERE
        GameObject printItem = Instantiate(printItemPrefab, printItemParent.transform);
        Debug.Log(_currentDepth);
    }
</code>```

Body:
I have a game I am developing in Unity where AI is doing large calculations when it is its turn. It searches the position to depth 1, then 2, then 3 etc. Between each depth I want to instantiate a Gameobject with info about the depth to UI. The problem is that nothing happens until the AI is completely finished, then all items are added at once. Here is some code to explain better:

private void AIMakeMove()
{
    for (int currentDepth = 1; currentDepth < maxDepth + 1; currentDepth++)
    {
        SearchPosition(currentDepth);
    }
}

private void SearchPosition(int _currentDepth)
{
    // Search the position to the given depth
    score = Negamax(_currentDepth);

     // Print things   PROBLEM HERE
    GameObject printItem = Instantiate(printItemPrefab, printItemParent.transform);
    Debug.Log(_currentDepth);
}

I also tried just a simple Debug.Log instead of Instantiate but same thing happens then, all prints to console happens after the AI is done with its thinking process.

Why is my UI not updating with information? I tell it to create some things after it run the first iteration with depth 0 but it skips this step and goes on depth 2 instead. Can someone please let me know how to get information out between each depth?

Body:
Try using a thread:

private void AIMakeMove()
    {
        new System.Threading.Thread(() =>
        {
            for (int currentDepth = 1; currentDepth < maxDepth + 1; currentDepth++)
            {
                SearchPosition(currentDepth);
            }
        }).Start();
    }

    private void SearchPosition(int _currentDepth)
    {
        // Search the position to the given depth
        score = Negamax(_currentDepth);

        // Print things   PROBLEM HERE
        GameObject printItem = Instantiate(printItemPrefab, printItemParent.transform);
        Debug.Log(_currentDepth);
    }


问:
datagridview / binding list / Binding Source binding takes forever
I'm trying something like the code below. The difference being the BindingSource and DataGridView are created by the designer of my Windows Forms form.

What happens is the data binding seems to hang. The operation is asynchronous, so the execution continues until you get an error because there are no columns on the datagridview

I think that is the problem because I placed breakpoint inside the dataGridView_DataBindingComplete event and it is never hit, or it takes a long time.

The data source is a list with a single item, so load should not be an issue. I also tried changing the order of the DataSource assignments but no luck.

```<code>public void OpenForm()
{
    L = new BindingList<conhecimento>();
    L.Add(new conhecimento());
    BS.DataSource=L;
    DG.DataSource = BS;
    myForm.Show()
}
</code>```

答:
Have you tried skipping the BindingSource and just doing:</p>

```<code>DG.DataSource = L
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying something like the code below. The difference being the BindingSource and DataGridView are created by the designer of my Windows Forms form.

What happens is the data binding seems to hang. The operation is asynchronous, so the execution continues until you get an error because there are no columns on the datagridview

I think that is the problem because I placed breakpoint inside the dataGridView_DataBindingComplete event and it is never hit, or it takes a long time.

The data source is a list with a single item, so load should not be an issue. I also tried changing the order of the DataSource assignments but no luck.

public void OpenForm()
{
    L = new BindingList<conhecimento>();
    L.Add(new conhecimento());
    BS.DataSource=L;
    DG.DataSource = BS;
    myForm.Show()
}

Body:
Have you tried skipping the BindingSource and just doing:

DG.DataSource = L


问:
How to query by non-primary key in AWS-amplify graphql schema
I have a graphql schema in aws-amplify, appsync.

my schema is:

```<code>type Project
  @model
  {
    id: ID!
    project_number: String!
    name: String!
    architect: String!
    interfaces: [Interface] @connection(name: "ProjectInterfaces")

  }
type Interface
  @model
  {
    id: ID!
    interface_name: String!
    version: String!
    release: String!
    source_feature: String!
    MFT_feature_id: String!
    state: String!
    source_application: String!
    source_env: String!
    source_go_live: String!
    source_payload: String!
    source_payload_format: String!
    source_payload_volume: String!
    source_protocol: String!
    target_application: String!
    target_env: String!
    target_go_live: String!
    target_payload: String!
    target_payload_format: String!
    target_payload_volume: String!
    target_protocol: String!
    frequency: String!
    authentication: String!
    payload_security: String!
    transport_security: String!
    network_paths: String!
    project: Project @connection(name: "ProjectInterfaces")
  }
</code>```

and I want to know if I can search a projects interfaces by project_number instead of id. I added an index on project_name, but it doesn't seem to work. My current query is

```<code>query GetProject {
  getProject(project_number:"P200") {
    name
    architect
    interfaces{
      items{
        interface_name
        version
        release
        source_feature
        MFT_feature_id
        state
        source_application
        source_env
        source_go_live
        source_payload
        source_payload_format
        source_payload_volume
        source_protocol
        target_application
        target_env
        target_go_live
        target_payload
        target_payload_format
        target_payload_volume
        target_protocol
        frequency
        authentication
        payload_security
        transport_security
        network_paths
      }
    }
  }
}
</code>```

Please let me know if this is possible. I would like it so that I can just search by project_name, and then get all the details from interface.

答:
So according to the Amplify docs you would have to add an @index on the field you'd like to query on.  I've updated your Project model to have an index on the project_number field.

```<code>type Project
  @model
  {
    id: ID!
    project_number: String! @index(name: "byProjectName", queryField: "projectByNumber", sortKeyFields: ["id"])
    name: String!
    architect: String!
    interfaces: [Interface] @connection(name: "ProjectInterfaces")
  }
</code>```

Then to query by project_number, use the query name set in the queryField (projectByNumber) in the index:

```<code>query projectByNumber($projectNumber: String!) {
  projectByNumber(project_number: $projectNumber) {
    items {
      id
      project_number
      name
      architect
      ...
    }
  }
}
</code>```

Please checkout the docs under Query employee details by employee name to get a better understanding: https://docs.amplify.aws/cli/graphql/examples-and-solutions/#2-query-employee-details-by-employee-name

Body:
I have a graphql schema in aws-amplify, appsync.

my schema is:

type Project
  @model
  {
    id: ID!
    project_number: String!
    name: String!
    architect: String!
    interfaces: [Interface] @connection(name: "ProjectInterfaces")

  }
type Interface
  @model
  {
    id: ID!
    interface_name: String!
    version: String!
    release: String!
    source_feature: String!
    MFT_feature_id: String!
    state: String!
    source_application: String!
    source_env: String!
    source_go_live: String!
    source_payload: String!
    source_payload_format: String!
    source_payload_volume: String!
    source_protocol: String!
    target_application: String!
    target_env: String!
    target_go_live: String!
    target_payload: String!
    target_payload_format: String!
    target_payload_volume: String!
    target_protocol: String!
    frequency: String!
    authentication: String!
    payload_security: String!
    transport_security: String!
    network_paths: String!
    project: Project @connection(name: "ProjectInterfaces")
  }

and I want to know if I can search a projects interfaces by project_number instead of id. I added an index on project_name, but it doesn't seem to work. My current query is

query GetProject {
  getProject(project_number:"P200") {
    name
    architect
    interfaces{
      items{
        interface_name
        version
        release
        source_feature
        MFT_feature_id
        state
        source_application
        source_env
        source_go_live
        source_payload
        source_payload_format
        source_payload_volume
        source_protocol
        target_application
        target_env
        target_go_live
        target_payload
        target_payload_format
        target_payload_volume
        target_protocol
        frequency
        authentication
        payload_security
        transport_security
        network_paths
      }
    }
  }
}

Please let me know if this is possible. I would like it so that I can just search by project_name, and then get all the details from interface.

Body:
So according to the Amplify docs you would have to add an @index on the field you'd like to query on.  I've updated your Project model to have an index on the project_number field.

type Project
  @model
  {
    id: ID!
    project_number: String! @index(name: "byProjectName", queryField: "projectByNumber", sortKeyFields: ["id"])
    name: String!
    architect: String!
    interfaces: [Interface] @connection(name: "ProjectInterfaces")
  }

Then to query by project_number, use the query name set in the queryField (projectByNumber) in the index:

query projectByNumber($projectNumber: String!) {
  projectByNumber(project_number: $projectNumber) {
    items {
      id
      project_number
      name
      architect
      ...
    }
  }
}

Please checkout the docs under Query employee details by employee name to get a better understanding: https://docs.amplify.aws/cli/graphql/examples-and-solutions/#2-query-employee-details-by-employee-name


问:
How do you work on Oracle packages in a collaborative, version-controlled environment?
I'm working in a multi-developer environment in Oracle with a large package.  We have a DEV => TST => PRD promotion pattern.  Currently, all package edits are made directly in TOAD and then compiled into the DEV package.

We run into two problems:

Concurrent changes need to be promoted on different schedules.  For instance, developer A makes a change that needs to be promoted tomorrow while developer B is concurrently working on a change that won't be promoted for another two weeks.  When it comes promotion time, we find ourselves manually commenting out stuff that isn't being promoted yet and then uncommenting it afterwards...yuck!!!

If two developers are making changes at the same exact time and one of them compiles, it wipes out the other developer's changes.  There isn't a nice merge; instead the latest compile wins.

What strategies would you recommend to get around this?  We are using TFS for our source-control but haven't yet utilized this with our Oracle packages.

P.S. I've seen this posting, but it doesn't fully answer my question.

答:
See my answer about Tools to work with stored procedures in Oracle, in a team (which I have just retagged).

Bottom line : don't modify procedures directly with TOAD. Store the source as files, that you will store in source control, modify then execute.

Plus, I would highly recommend that each developer works on its own copy of the database (use Oracle Express, which is free). You can do that if you store all the scripts to create the database in source control. More insight can be found here.

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: JB King

OwnerDisplayName: Mac


问:
If I convert a python file from py to exe, what about the module I created that the file imports?

I created a server and client file and I was about to convert it to exe when I realized that I also need to convert the module it uses to exe. What do I do about the module?

答:
It looks like Auto PY to EXE uses PyInstaller to do the real work here:

A .py to .exe converter using a simple graphical interface and PyInstaller in Python.

PyInstaller will automatically bundle any dependencies it finds:

What other modules and libraries does your script need in order to run? (These are sometimes called its "dependencies".)

To find out, PyInstaller finds all the import statements in your script. It finds the imported modules and looks in them for import statements, and so on recursively, until it has a complete list of modules your script may use.

So as long as you import your dependencies somewhere reachable from your main script and your virtual environment is active, you should get the right behaviour automatically.

Note that you'll probably need to build two executables: one for your server and a separate one for your client.


问:
Regular Expression to find \"
What's the regular expression to find \"

I think it's this: '/\\"/' but I need to use it on a really large dataset so need to make sure this is correct.

I need to replace it with " so my code is : $data = preg_replace('/\\"/', '"', $data)

Is that correct?

答:
```<code>$result = preg_replace('/\\\\"/i', '"', $subject);
</code>```

Title: Regular Expression to find \"


问:
How to achieve a thread-safe or immutable collection in fastutils?
Fastutil seems to be the fastest option for collections in Java.

There are these javadocs:
http://fastutil.di.unimi.it/docs/it/unimi/dsi/fastutil/longs/Long2ObjectMaps.SynchronizedMap.html

but I have difficulty to find the usage example.

How can I have a synchronized (thread-safe?) map? An immutable map?

答:
There is a lightweight thread-safe alternative: FastUtil Concurrent Wrapper .

Compared to the default fastutil synchronization approach via synchronized(mutex) The Wrapper uses striped ReadWriteLocks (with different modes) which have better performance in some cases.


问:
Changes in the column values for machine learning
Below shown is the engine column that I have taken from a data set

engine

2150 cc

2240 cc

2150 cc

2230 cc

2050 cc

2280 cc

I want my column engine to be like as shown below:

engine

2150

2240

2150

2230

2050

2280

答:
You can extract the leading digits with a regex:

```<code>df['engine'] = df['engine'].str.extract('(^\d+)')
</code>```

output:

```<code>  engine
0   2150
1   2240
2   2150
3   2230
4   2050
5   2280
</code>```

If you need integers:

```<code>df['engine'] = df['engine'].str.extract('(^\d+)').astype(int)
</code>```

Body:
You can extract the leading digits with a regex:

df['engine'] = df['engine'].str.extract('(^\d+)')

output:

  engine
0   2150
1   2240
2   2150
3   2230
4   2050
5   2280

If you need integers:

df['engine'] = df['engine'].str.extract('(^\d+)').astype(int)


问:
WorkManager wait for upload to finish before moving on to the next work request
I'm using WorkManager in my Android app.
I've set a work request and in its doWork() method I'm uploading a file to Firebase Storage.
I want to chain this work request with another one, but I need the upload to finish (in order to get the download URL) before the next request starts (before I return Result.success).
How can I achieve this work?
Can I use LiveData inside the doWork() method?
How can I wait for the callback before I return the work's result?

*By the way, I'm trying to avoid redundant firebase calls, so the option for writing to the database, then update the database with the URL I get doesn't work for me.

Code:

```<code>class UploadWorker(context: Context, workerParams: WorkerParameters): Worker(context,workerParams)
{
    override fun doWork(): Result
    {
        //get input
        ...
        //store file in Firebase
        val storage = FirebaseStorage.getInstance()
        val storageRef = storage.reference
        val fileRef = storageRef.child(filePath.toString())

        val uploadTask = fileRef.putBytes(file)
        var downloadFileUrl: String? = ""

        uploadTask.continueWithTask { task ->
            if (!task.isSuccessful)
            {
                task.exception?.let { throw it }
            }
            fileRef.downloadUrl
        }.addOnCompleteListener { task ->
            if (task.isSuccessful)
            {
                //this is what I want to save before the return of doWork()
                downloadFileUrl = task.result.toString()
            }
            else
            {
                // Handle failures
                Log.d("fb", "fail")
            }
        }

        return Result.success()
    }
}
</code>```

答:
If anyone else faces the same issue later on, what you need to use is the storage reference, not the upload task</p>
```<code>override fun doWork(): Result{
    .....
    val downloadUriTask = Tasks.await(imageRef.downloadUrl)
    val url = downloadUriTask.toString()
    ....
    return Result.success()
}
</code>```

Body:
I'm using WorkManager in my Android app.
I've set a work request and in its doWork() method I'm uploading a file to Firebase Storage.
I want to chain this work request with another one, but I need the upload to finish (in order to get the download URL) before the next request starts (before I return Result.success).
How can I achieve this work?
Can I use LiveData inside the doWork() method?
How can I wait for the callback before I return the work's result?

*By the way, I'm trying to avoid redundant firebase calls, so the option for writing to the database, then update the database with the URL I get doesn't work for me.

Code:

class UploadWorker(context: Context, workerParams: WorkerParameters): Worker(context,workerParams)
{
    override fun doWork(): Result
    {
        //get input
        ...
        //store file in Firebase
        val storage = FirebaseStorage.getInstance()
        val storageRef = storage.reference
        val fileRef = storageRef.child(filePath.toString())

        val uploadTask = fileRef.putBytes(file)
        var downloadFileUrl: String? = ""

        uploadTask.continueWithTask { task ->
            if (!task.isSuccessful)
            {
                task.exception?.let { throw it }
            }
            fileRef.downloadUrl
        }.addOnCompleteListener { task ->
            if (task.isSuccessful)
            {
                //this is what I want to save before the return of doWork()
                downloadFileUrl = task.result.toString()
            }
            else
            {
                // Handle failures
                Log.d("fb", "fail")
            }
        }

        return Result.success()
    }
}

Body:
If anyone else faces the same issue later on, what you need to use is the storage reference, not the upload task

override fun doWork(): Result{
    .....
    val downloadUriTask = Tasks.await(imageRef.downloadUrl)
    val url = downloadUriTask.toString()
    ....
    return Result.success()
}


问:
Getting a TypError saying that my exported function is not a function with nodejs
My goal is to create a discord bot that plays Spotify music, but when I run the function that plays music it gives me the error:

TypeError: playSong is not a function

Here is what is in my api.js:

```<code>const playSong = (songName) => {
    spotifyApi.searchTracks(songName)
        .then(data => {
            const track = data.body.tracks.items[0];
            const trackId = track.id;
            spotifyApi.play({
                device_id: '',
                uris: [`spotify:track:${trackId}`]
            });
        })
        .catch(err => {
            console.error(err);

        });
};

module.exports = { playSong };
</code>```

And here is in my play.js:

```<code>const { playSong } = require('../spotify_api/api.js');

let msg = message.content
        let song = msg.replace('!play ', '');

        //creates the audio player
        if (message.content === `!play ${song}`) {
            //VoiceChannel IDs

            //Audio Player
            const player = createAudioPlayer()
            player.on(AudioPlayerStatus.Playing, () => {
                client.message.reply(`Now playing: ${song}`)
                console.log(`Now playing: ${song}`)
            })

            player.on('error', err => {
                console.log(`Error: ${err.message} with resource`)
            })

            //creat and play audio
            player.play(playSong(song)); //This is where I call the function

            //Subscribe the connection to the audio player
            const subscription = connection.subscribe(player)

            if (subscription) {
                //Unsubscribe the subscription
                setTimeout(() => subscription.unsubscribe(), 120000)
            }

        }
</code>```

I have tried to use other methods I know of but it all comes down to the same TypeError. T_T

答:
Try to replace

```<code>const playSong = () =>
</code>```

with

```<code>function playSong()
</code>```

Body:
My goal is to create a discord bot that plays Spotify music, but when I run the function that plays music it gives me the error:

TypeError: playSong is not a function

Here is what is in my api.js:

const playSong = (songName) => {
    spotifyApi.searchTracks(songName)
        .then(data => {
            const track = data.body.tracks.items[0];
            const trackId = track.id;
            spotifyApi.play({
                device_id: '',
                uris: [`spotify:track:${trackId}`]
            });
        })
        .catch(err => {
            console.error(err);

        });
};

module.exports = { playSong };

And here is in my play.js:

const { playSong } = require('../spotify_api/api.js');

let msg = message.content
        let song = msg.replace('!play ', '');

        //creates the audio player
        if (message.content === `!play ${song}`) {
            //VoiceChannel IDs

            //Audio Player
            const player = createAudioPlayer()
            player.on(AudioPlayerStatus.Playing, () => {
                client.message.reply(`Now playing: ${song}`)
                console.log(`Now playing: ${song}`)
            })

            player.on('error', err => {
                console.log(`Error: ${err.message} with resource`)
            })

            //creat and play audio
            player.play(playSong(song)); //This is where I call the function

            //Subscribe the connection to the audio player
            const subscription = connection.subscribe(player)

            if (subscription) {
                //Unsubscribe the subscription
                setTimeout(() => subscription.unsubscribe(), 120000)
            }

        }

I have tried to use other methods I know of but it all comes down to the same TypeError. T_T

Body:
Try to replace

const playSong = () =>

with

function playSong()


问:
Recursive map function for nested array
I'm trying to create a map function that supports computing nested arrays, using recursion:

This function, when a unidimesional (eg. [1,2,3,4] ) array is used works fine:

```<code>const map = (oldArray, callback, newArray = []) => {

    //base case: check if there are any items left in the original array to process
    if (oldArray.length <= 0){
      //if all items have been processed return the new array
      return newArray
    } else {
      //destructure the first item from old array and put remaining in a separate array
      const [item, ...theRest] = oldArray
      // create an array of the current new array and the result of the current item and the callback function
      const interimArray = [...newArray, callback(item)]
      // return a recursive call to to map to process the next item.
      return map(theRest, callback, interimArray)
    }

  }
</code>```

But, I want to support a nested array, so for example, I have an array like this:

```<code>const array = [1,[1,2],3]
</code>```

and I want to apply a function, eg: (x)=>x+1;

I have this implementation so far, but I can't wrap my mind around it.

```<code>function rnMap(oldArr, fn, newArr = []) {
  const [item, ...rest] = oldArr;

  if (oldArr.length <= 0) {
    return newArr;
  } else if (Array.isArray(item)) {
    return rnMap(item, fn, [...newArr, rnMap(item, fn, [])]);
  } else {
    const interimArray = [...newArr, fn(item)];

    return rnMap(rest, fn, interimArray);
  }
}

const rnRes = rnMap(nArr, (e) => {
  return e + 1;
});

console.log(rnRes);
</code>```

It returns [ 2, [ 2, 2 ], 2, 2 ] but it suppose to return [2,[2,3],4]

If anyone could help me will be appretiated.
Thanks in advance.

答:
No loop approach, sort of ...

const
    map = ([value, ...array], fn) => {
        if (value === undefined) return [];
        return [
            (Array.isArray(value) ? map(value, fn) : fn(value)),
            ...map(array, fn)
        ];
    },
    array = [1, [1, 2], 3],
    fn = x => x + 1;

console.log(map(array, fn));```

Title: Recursive map function for nested array

Body:
I'm trying to create a map function that supports computing nested arrays, using recursion:

This function, when a unidimesional (eg. [1,2,3,4] ) array is used works fine:

const map = (oldArray, callback, newArray = []) => {

    //base case: check if there are any items left in the original array to process
    if (oldArray.length <= 0){
      //if all items have been processed return the new array
      return newArray
    } else {
      //destructure the first item from old array and put remaining in a separate array
      const [item, ...theRest] = oldArray
      // create an array of the current new array and the result of the current item and the callback function
      const interimArray = [...newArray, callback(item)]
      // return a recursive call to to map to process the next item.
      return map(theRest, callback, interimArray)
    }

  }

But, I want to support a nested array, so for example, I have an array like this:

const array = [1,[1,2],3]

and I want to apply a function, eg: (x)=>x+1;

I have this implementation so far, but I can't wrap my mind around it.

function rnMap(oldArr, fn, newArr = []) {
  const [item, ...rest] = oldArr;

  if (oldArr.length <= 0) {
    return newArr;
  } else if (Array.isArray(item)) {
    return rnMap(item, fn, [...newArr, rnMap(item, fn, [])]);
  } else {
    const interimArray = [...newArr, fn(item)];

    return rnMap(rest, fn, interimArray);
  }
}

const rnRes = rnMap(nArr, (e) => {
  return e + 1;
});

console.log(rnRes);

It returns [ 2, [ 2, 2 ], 2, 2 ] but it suppose to return [2,[2,3],4]

If anyone could help me will be appretiated.
Thanks in advance.


问:
Post method via Airtable API using a Google Script
I have the following code in a Google Script:

```<code>var data = {
    "records": [
          {
          "fields": {
              "Contract Address": "test",
              "0x8df3aad3a84da6b69a4da8aec3ea40d9091b2ac4": "1234"
          }
          }
    ]
};

var options = {
  "method" : "post",
  'Content-Type': 'application/json',
  'muteHttpExceptions' : true,
  // "payload" : data,
  "payload" : JSON.stringify(data)
};

function tryAPost(){
  var url = "https://api.airtable.com/v0/xxxxxxxxxxxxx/Balance%20Tracking?api_key=keyxxxxxxxxxx";
  var response = UrlFetchApp.fetch(url, options);
  //console.log(response.getContentText());
 console.log(response.getResponseCode());
};
</code>```

I get the following response:

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

And the data does not end up in Airtable.

The payload works in the body of a post request in Postman.

What am I doing wrong?

EDIT Per Comment:

here's the exmaple code from airtable:

```<code>var Airtable = require('airtable');
var base = new Airtable({apiKey: 'YOUR_API_KEY'}).base('xxxxxxxxxxxx');

base('Balance Tracking').create([
  {
    "fields": {
      "Contract Address": "Thu, 03 Feb 2022 15:12:37 GMT",
      "0xfecf784f48125ccb7d8855cdda7c5ed6b5024cb3": 12055358359168
</code>```

Adding postman screenshot per comment:

答:
I asked in the Airtable Forum and someone came up with a solution that worked.

Here's the link.

Here's the answer:

```<code>//
// post to Airtable (universal)
//
function atPostTable_(baseKey, tableName, payload)
{
  var options =
      {
        method: 'POST',
        headers: {
          'Authorization' : 'Bearer ' + cMyAirtableAPIKey,
          'Content-Type'  : 'application/json'
        },
        payload : JSON.stringify(payload),
        muteHttpExceptions : true,
        followRedirects: true
      };
  var response = UrlFetchApp.fetch(cAirtableAPIEndpoint + baseKey + "/" + encodeURIComponent(tableName), options).getContentText();
  return(response);
}

</code>```

Body:
I have the following code in a Google Script:

var data = {
    "records": [
          {
          "fields": {
              "Contract Address": "test",
              "0x8df3aad3a84da6b69a4da8aec3ea40d9091b2ac4": "1234"
          }
          }
    ]
};

var options = {
  "method" : "post",
  'Content-Type': 'application/json',
  'muteHttpExceptions' : true,
  // "payload" : data,
  "payload" : JSON.stringify(data)
};

function tryAPost(){
  var url = "https://api.airtable.com/v0/xxxxxxxxxxxxx/Balance%20Tracking?api_key=keyxxxxxxxxxx";
  var response = UrlFetchApp.fetch(url, options);
  //console.log(response.getContentText());
 console.log(response.getResponseCode());
};

I get the following response:

422

And the data does not end up in Airtable.

The payload works in the body of a post request in Postman.

What am I doing wrong?

EDIT Per Comment:

here's the exmaple code from airtable:

var Airtable = require('airtable');
var base = new Airtable({apiKey: 'YOUR_API_KEY'}).base('xxxxxxxxxxxx');

base('Balance Tracking').create([
  {
    "fields": {
      "Contract Address": "Thu, 03 Feb 2022 15:12:37 GMT",
      "0xfecf784f48125ccb7d8855cdda7c5ed6b5024cb3": 12055358359168

Adding postman screenshot per comment:

Body:
I asked in the Airtable Forum and someone came up with a solution that worked.

Here's the link.

Here's the answer:

//
// post to Airtable (universal)
//
function atPostTable_(baseKey, tableName, payload)
{
  var options =
      {
        method: 'POST',
        headers: {
          'Authorization' : 'Bearer ' + cMyAirtableAPIKey,
          'Content-Type'  : 'application/json'
        },
        payload : JSON.stringify(payload),
        muteHttpExceptions : true,
        followRedirects: true
      };
  var response = UrlFetchApp.fetch(cAirtableAPIEndpoint + baseKey + "/" + encodeURIComponent(tableName), options).getContentText();
  return(response);
}


问:
docker not found with docker:dind + google/cloud-sdk
I'm getting the error docker: command not found while running the following CI script inside gitlab-ci. This error is happening during before_script for the deploy phase.

```<code>services:
  - docker:dind

stages:
  - build
  - test
  - deploy

before_script:
  - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY

build:
  stage: build
  image: docker:latest
  script:
    - docker info
    - docker version
    - docker build --pull -t $SERVICE_NAME:$CI_COMMIT_REF_NAME .
    - docker image list
    - docker tag $SERVICE_NAME:$CI_COMMIT_REF_NAME $CI_REGISTRY_IMAGE/$SERVICE_NAME:$CI_COMMIT_REF_NAME
    - docker push $CI_REGISTRY_IMAGE/$SERVICE_NAME:$CI_COMMIT_REF_NAME

test:
  image: docker:latest
  stage: test
  script:
    - docker pull $CI_REGISTRY_IMAGE/$SERVICE_NAME:$CI_COMMIT_REF_NAME
    - docker image list
    - docker run $CI_REGISTRY_IMAGE/$SERVICE_NAME:$CI_COMMIT_REF_NAME npm test

deploy:
  image: google/cloud-sdk
  stage: deploy
  environment: Production
  script:
    - echo $DEPLOY_KEY_FILE_PRODUCTION > /tmp/GCLOUD_KEYFILE.json
    - gcloud auth activate-service-account --key-file /tmp/GCLOUD_KEYFILE.json
    - rm /tmp/GCLOUD_KEYFILE.json
    - gcloud info
    - gcloud components list
  only:
    - master
</code>```

I'm a bit confused, because I'm runing docker-in-docker (docker:dind) as a service so the docker command should be made available to all stages (if I understand this correctly), however it's clearly not.

Is it due to an interaction with google/cloud-sdk ?

答:
The question was asked almost 5 years ago, I am unsure if by that time the image google/cloud-sdk shipped without docker binaries, I can't think of anything else for a docker: command not found error more than it was not available in the standard location. Anyways, today 2022 google/cloud-sdk comes with docker and it can interact with the docker service, and since I ended up here several times after running into problems trying to use docker:dind and google/cloud-sdk, I will add the following:

Is possible to use docker from the google/cloud-sdk image, there is no need to create a custom image for your Gitlab CI. The problem is that docker in google/cloud-sdk tries to connect to the socket in /var/run/docker.sock as is presented in the logs:

$ docker build -t gcr.io/$GCP_PROJECT_ID/test:$CI_COMMIT_SHORT_SHA .
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
```
<p>Anyways you can also checks in your logs of the service <code>docker:dind</code> that docker listens in a socket (not reachable from the job container) and a tcp port (reachable via the hostname <code>docker</code>). So, you just need to use the tcp port in your docker commands, either by setting the env variable <code>DOCKER_HOST</code> or adding a <code>-H tcp://docker:2375</code> as in</p>
<pre class="lang-sh prettyprint-override"><code>$ docker -H tcp://docker:2375 build -t gcr.io/$GCP_PROJECT_ID/test:$CI_COMMIT_SHORT_SHA .
Step 1/8 : FROM python:latest
</code>```

Body:
I'm getting the error docker: command not found while running the following CI script inside gitlab-ci. This error is happening during before_script for the deploy phase.

services:
  - docker:dind

stages:
  - build
  - test
  - deploy

before_script:
  - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY

build:
  stage: build
  image: docker:latest
  script:
    - docker info
    - docker version
    - docker build --pull -t $SERVICE_NAME:$CI_COMMIT_REF_NAME .
    - docker image list
    - docker tag $SERVICE_NAME:$CI_COMMIT_REF_NAME $CI_REGISTRY_IMAGE/$SERVICE_NAME:$CI_COMMIT_REF_NAME
    - docker push $CI_REGISTRY_IMAGE/$SERVICE_NAME:$CI_COMMIT_REF_NAME

test:
  image: docker:latest
  stage: test
  script:
    - docker pull $CI_REGISTRY_IMAGE/$SERVICE_NAME:$CI_COMMIT_REF_NAME
    - docker image list
    - docker run $CI_REGISTRY_IMAGE/$SERVICE_NAME:$CI_COMMIT_REF_NAME npm test

deploy:
  image: google/cloud-sdk
  stage: deploy
  environment: Production
  script:
    - echo $DEPLOY_KEY_FILE_PRODUCTION > /tmp/GCLOUD_KEYFILE.json
    - gcloud auth activate-service-account --key-file /tmp/GCLOUD_KEYFILE.json
    - rm /tmp/GCLOUD_KEYFILE.json
    - gcloud info
    - gcloud components list
  only:
    - master

I'm a bit confused, because I'm runing docker-in-docker (docker:dind) as a service so the docker command should be made available to all stages (if I understand this correctly), however it's clearly not.

Is it due to an interaction with google/cloud-sdk ?

Body:
The question was asked almost 5 years ago, I am unsure if by that time the image google/cloud-sdk shipped without docker binaries, I can't think of anything else for a docker: command not found error more than it was not available in the standard location. Anyways, today 2022 google/cloud-sdk comes with docker and it can interact with the docker service, and since I ended up here several times after running into problems trying to use docker:dind and google/cloud-sdk, I will add the following:

Is possible to use docker from the google/cloud-sdk image, there is no need to create a custom image for your Gitlab CI. The problem is that docker in google/cloud-sdk tries to connect to the socket in /var/run/docker.sock as is presented in the logs:

$ docker build -t gcr.io/$GCP_PROJECT_ID/test:$CI_COMMIT_SHORT_SHA .
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

Anyways you can also checks in your logs of the service docker:dind that docker listens in a socket (not reachable from the job container) and a tcp port (reachable via the hostname docker). So, you just need to use the tcp port in your docker commands, either by setting the env variable DOCKER_HOST or adding a -H tcp://docker:2375 as in

$ docker -H tcp://docker:2375 build -t gcr.io/$GCP_PROJECT_ID/test:$CI_COMMIT_SHORT_SHA .
Step 1/8 : FROM python:latest


问:
glfwDestroyWindow won't close window
I have a program with OpenGL running in a secondary thread. If the render loop is done, I call glfwDestroyWindow(). However, the window won't close before I exit the main thead. If I try to close it several times (by repeatedly clicking on the x), a window pops up that says the window is not responding and asks me to force quit.

Why does glfwDestroyWindow not properly close my window?

EDIT: By the way, I am using GLFW3.

EDIT2:

This is how my code looks like, basically. I can see the output while the window is still open. The window is only closed when I either force close it or exit the main thread.

Main thread:

```<code>int main() {
    startOpenGLThread();
    while(1);
}
</code>```

OpenGL thread:

```<code>Window::start() {
    initGLFW();
    while(!glfwWindowShouldClose());
    glfwDestroyWindow();
    cout << "I can see this ouput, but the window is still open!" << endl;
}
</code>```

EDIT3:

The window closes if I put the glfwTerminate() right behind the output, obviously. However, this is not what I want, because I may have other windows opened.

答:
You can try to close the window first in this way:</p>
```<code>glfwSetWindowShouldClose(win, true);
glfwDestroyWindow(win);
</code>```

Title: glfwDestroyWindow won't close window

Body:
I have a program with OpenGL running in a secondary thread. If the render loop is done, I call glfwDestroyWindow(). However, the window won't close before I exit the main thead. If I try to close it several times (by repeatedly clicking on the x), a window pops up that says the window is not responding and asks me to force quit.

Why does glfwDestroyWindow not properly close my window?

EDIT: By the way, I am using GLFW3.

EDIT2:

This is how my code looks like, basically. I can see the output while the window is still open. The window is only closed when I either force close it or exit the main thread.

Main thread:

int main() {
    startOpenGLThread();
    while(1);
}

OpenGL thread:

Window::start() {
    initGLFW();
    while(!glfwWindowShouldClose());
    glfwDestroyWindow();
    cout << "I can see this ouput, but the window is still open!" << endl;
}

EDIT3:

The window closes if I put the glfwTerminate() right behind the output, obviously. However, this is not what I want, because I may have other windows opened.

Body:
You can try to close the window first in this way:

glfwSetWindowShouldClose(win, true);
glfwDestroyWindow(win);


问:
How to convert object to Dictionary<TKey, TValue> in C#?
How do I convert a dynamic object to a Dictionary<TKey, TValue> in C# What can I do?

```<code>public static void MyMethod(object obj)
{
    if (typeof(IDictionary).IsAssignableFrom(obj.GetType()))
    {
        // My object is a dictionary, casting the object:
        // (Dictionary<string, string>) obj;
        // causes error ...
    }
    else
    {
        // My object is not a dictionary
    }
}
</code>```

答:
This way for object array to Dictionary<string, object> List coverting

```<code>object[] a = new object[2];
var x = a.Select(f => (Dictionary<string, object>)f).ToList();
</code>```

This way for single object to Dictionary<string, object>  coverting

```<code>object a = new object;
var x = (Dictionary<string, object>)a;
</code>```

Body:
How do I convert a dynamic object to a Dictionary<TKey, TValue> in C# What can I do?

public static void MyMethod(object obj)
{
    if (typeof(IDictionary).IsAssignableFrom(obj.GetType()))
    {
        // My object is a dictionary, casting the object:
        // (Dictionary<string, string>) obj;
        // causes error ...
    }
    else
    {
        // My object is not a dictionary
    }
}

Body:
This way for object array to Dictionary<string, object> List coverting

object[] a = new object[2];
var x = a.Select(f => (Dictionary<string, object>)f).ToList();

This way for single object to Dictionary<string, object>  coverting

object a = new object;
var x = (Dictionary<string, object>)a;


问:
C# Delegates to methods with different optional parameters
I know that I can declare delegates that have default constant parameters such as:

```<code>delegate void MyDelegate(int x, int y = 5);
</code>```

and then call it anywhere with any method that matches the signature.

Ok, I've got LOTS of methods declared like this way:

```<code>public Something FirstMethod(float val = 10, int skip = 0){ ... return sth; }
public Something SecondMethod(float val = 20, int skip = 0){ ... return sth; }
public Something ThirdMethod(float val = 5, int skip = 0){ ... return sth; }
</code>```

... this list goes up all the way down, anyway, they all have that signature structure. The point here is that, they all have floating point argument, that defaults to something different.

Then, I want to create a delegate that will point to one of these methods:

```<code>delegate Something ProblematicDelegateType(<<WHAT WILL GO HERE>>);
ProblematicDelegateType myFunc;
if(someValue == someParameter){
    myFunc = FirstMethod;
}else if(...){
    myFunc = SecondMethod;
}else...
...
}

myFunc();
myFunc(skip:100);
</code>```

I want to be able to call myFunc both parameterless or with the skip parameter. In this part of code, the first parameter, val, is NOT used. (they are used elsewhere).

What will go to the delegate's argument list? I want to preserve that method's default val argument, whatever it is.

答:
Your requirement that the delegate have an optional parameter that varies depending on the method it invokes can't be done. Optional parameters are implemented by rewriting the call site of the method when it is compiled. If the method the delegate points to is determined at run-time what would it write at compile-time? Eric Lippert's series on optional arguments is very enlightening.

However, you could also look into using reflection to get the default value. Use MethodInfo.GetParameters() to get the parameter info and ParameterInfo.DefaultValue to get the default value.

Body:
I know that I can declare delegates that have default constant parameters such as:

delegate void MyDelegate(int x, int y = 5);

and then call it anywhere with any method that matches the signature.

Ok, I've got LOTS of methods declared like this way:

public Something FirstMethod(float val = 10, int skip = 0){ ... return sth; }
public Something SecondMethod(float val = 20, int skip = 0){ ... return sth; }
public Something ThirdMethod(float val = 5, int skip = 0){ ... return sth; }

... this list goes up all the way down, anyway, they all have that signature structure. The point here is that, they all have floating point argument, that defaults to something different.

Then, I want to create a delegate that will point to one of these methods:

delegate Something ProblematicDelegateType(<<WHAT WILL GO HERE>>);
ProblematicDelegateType myFunc;
if(someValue == someParameter){
    myFunc = FirstMethod;
}else if(...){
    myFunc = SecondMethod;
}else...
...
}

myFunc();
myFunc(skip:100);

I want to be able to call myFunc both parameterless or with the skip parameter. In this part of code, the first parameter, val, is NOT used. (they are used elsewhere).

What will go to the delegate's argument list? I want to preserve that method's default val argument, whatever it is.


问:
React Material Tabs content gets shifted to the out of the expected Container
I want to implement the Tabs Component for my React Website. I got the Problem, that the content I want to display in the red / blue Container gets shifted to the bottom for the blue container. I know the Problem comes from the red box, which is invisible but somehow is still there and shifts my content to the bottom.

The JSX looks like the following:

```<code>        <div className='drinks'>
            <Header />
            <div className="drinks-tabs-wrapper">
                <Tabs value={tab} onChange={ (_, value) => setTab(value) }>
                    <Tab label='Drinks' style={{ color: 'white' }} />
                    <Tab label='Categories' style={{ color: 'white' }} />
                </Tabs>
                <div style={ getTabWrapperStyle('drinks') }>
                    { (!drinks || !drinkCategories) ?
                    <CircularProgress size={ 100 } /> :
                    <div hidden={ tab !== 0 }>
                        { drinks.map(drink => (
                            <div key={ drink.id }>
                                <p>{ drink.id }</p>
                                <p>{ drink.name }</p>
                                <p>{ drink.price }</p>
                            </div>
                        ))}
                    </div> }
                </div>
                <div style={ getTabWrapperStyle('drinkCategories') }>
                { drinkCategories &&
                    <div hidden={ tab !== 1 }>
                        { drinkCategories.map(drinkCategory => (
                            <div key={ drinkCategory.id }>
                                <p>{ drinkCategory.name }</p>
                            </div>
                        ))}
                    </div> }
                </div>
            </div>
        </div>
</code>```

The drinks and drinkCategories come from an API (therefore the Loader)

The getTabWrapperStyle which gets the CSS looks like the following:

```<code>    const getTabWrapperStyle = (tabName) => {
        if (tabName === 'drinks') {
            if (tab !== 0) {
                return {
                    "display": "flex",
                    "alignItems": "center",
                    "justifyContent": "center",
                    "height": "calc(100% - 50px)",
                    "background": "blue",
                    "overflowY": "scroll"
                }
            } else if (tab !== 1) {
                return {
                    "height": 0
                }
            }
        } else if (tabName === 'drinkCategories') {
            if (tab !== 0) {
                return {
                    "height": 0
                }
            } else if (tab !== 1) {
                return {
                    "display": "flex",
                    "alignItems": "center",
                    "justifyContent": "center",
                    "height": "calc(100% - 50px)",
                    "background": "red",
                    "overflowY": "scroll"
                }
            }
        }
    }
</code>```

Everything looks fine for the red box, but the blue one doesn't work.
The shifting looks like the following:

[1

答: Turned out the Problem was the display: flex in the blue / red containers css. Just remove this and work without the flex property and everything works fine.</p>

Body:
I want to implement the Tabs Component for my React Website. I got the Problem, that the content I want to display in the red / blue Container gets shifted to the bottom for the blue container. I know the Problem comes from the red box, which is invisible but somehow is still there and shifts my content to the bottom.

The JSX looks like the following:

                <Tabs value={tab} onChange={ (_, value) => setTab(value) }>
                    <Tab label='Drinks' style={{ color: 'white' }} />
                    <Tab label='Categories' style={{ color: 'white' }} />
                </Tabs>

                    { (!drinks || !drinkCategories) ?
                    <CircularProgress size={ 100 } /> :

                        { drinks.map(drink => (

{ drink.id }

{ drink.name }

{ drink.price }

                        ))}

 }

                { drinkCategories &&

                        { drinkCategories.map(drinkCategory => (

{ drinkCategory.name }

                        ))}

 }

The drinks and drinkCategories come from an API (therefore the Loader)

The getTabWrapperStyle which gets the CSS looks like the following:

    const getTabWrapperStyle = (tabName) => {
        if (tabName === 'drinks') {
            if (tab !== 0) {
                return {
                    "display": "flex",
                    "alignItems": "center",
                    "justifyContent": "center",
                    "height": "calc(100% - 50px)",
                    "background": "blue",
                    "overflowY": "scroll"
                }
            } else if (tab !== 1) {
                return {
                    "height": 0
                }
            }
        } else if (tabName === 'drinkCategories') {
            if (tab !== 0) {
                return {
                    "height": 0
                }
            } else if (tab !== 1) {
                return {
                    "display": "flex",
                    "alignItems": "center",
                    "justifyContent": "center",
                    "height": "calc(100% - 50px)",
                    "background": "red",
                    "overflowY": "scroll"
                }
            }
        }
    }

Everything looks fine for the red box, but the blue one doesn't work.
The shifting looks like the following:

[1


问:
Android 12 - Emulator (Xamarin.Android )
I have been trying to find some reliable solution to this but I couldn't. I have added Android 11 - S which is an Android 12 Beta image in Android SDKs as shown in the following screenshot

But when I go and try to create the Emulator device in Device Manager I don't see this API in the list

What Am I doing wrong here?

答: In VS2022 17.0.5, Android 12 is available as a choice in the emulators list. However, be warned. Debugging/deploying android Xamarin in VS 2022 as of this version is sloowwwwww. Anyone with any leads on that, please hit me up!</p>


问:
Doing like roslaunch in C++ : Launch NodeHandle with specific type
I'm new to ROS and i'm looking for launching a 'video_stream_opencv' node programatically.

Link below :
http://wiki.ros.org/video_stream_opencv

the launch file is working well with the commands roslaunch

```<code><!-- images will be published at /camera_name/image with the image transports plugins (e.g.: compressed) installed -->
<group ns="$(arg camera_name)">
    <node pkg="video_stream_opencv" type="video_stream" name="$(arg camera_name)_stream" output="screen">
        <remap from="camera" to="image_raw" />
        <param name="camera_name" type="string" value="$(arg camera_name)" />
        <param name="video_stream_provider" type="string" value="$(arg video_stream_provider)" />
        <param name="fps" type="int" value="$(arg fps)" />
        <param name="frame_id" type="string" value="$(arg frame_id)" />
        <param name="camera_info_url" type="string" value="$(arg camera_info_url)" />
        <param name="flip_horizontal" type="bool" value="$(arg flip_horizontal)" />
        <param name="flip_vertical" type="bool" value="$(arg flip_vertical)" />
        <param name="width" type="int" value="$(arg width)" />
        <param name="height" type="int" value="$(arg height)" />
    </node>

    <node if="$(arg visualize)" name="$(arg camera_name)_image_view" pkg="image_view" type="image_view">
        <remap from="image" to="image_raw" />
    </node>
</group>
</code>```

But now i'm trying to do the same with C++ code but i don't see how to set the 'type' attributes in my node...

```<code>printf("Started ROS thread\n");

//glutInit(&argc, argv);

ros::init(argc, argv, "camera_name);
ROS_INFO("camera_name started");

// MY params to set
std::string camera_name = "toto";
std::string video_stream_provider = "toto";
int  fps  = 30;
std::string  frame_id= "toto";
std::string  camera_info_url= "toto";
bool flip_horizontal= false;
bool flip_vertical= false;
int width = 30;
int height = 30;

ros::NodeHandle nh;
ros::M_string remappings;
remappings.insert(std::make_pair("camera", "image_raw"));
ros::NodeHandle node_handle(nh, "camera_name",remappings);

node_handle.setParam("type",video_stream);
node_handle.setParam("camera_name",camera_name);
node_handle.setParam("video_stream_provider",video_stream_provider );
node_handle.setParam("fps",fps);
node_handle.setParam("frame_id",frame_id);
node_handle.setParam("camera_info_url", camera_info_url);
node_handle.setParam("flip_horizontal", flip_horizontal);
node_handle.setParam("flip_vertical",flip_vertical);
node_handle.setParam("width", width);
node_handle.setParam("height", height);
</code>```

答:
Reviving an old thread to help those in need.

I have created a class for this purpose that is based upon "rosspawn".

ros_launch_manager.hpp:

```<code>#pragma once

#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>

#include <cstdint>
#include <memory>
#include <thread>
#include <mutex>
#include <vector>
#include <algorithm>
#include <numeric>

#include "ros/ros.h"
#include "ros/console.h"
#include "rospack/rospack.h"

class ROSLaunchManager
{
    std::vector<pid_t> m_pids;

    std::atomic<bool> m_running;
    std::thread m_thread;
    std::mutex m_mutex;

public:
    ROSLaunchManager(ROSLaunchManager const &)
    {
    }

    ROSLaunchManager()
    {
        std::atomic_init(&m_running, true);

        m_thread = std::thread(&ROSLaunchManager::wait, this);
    }

    ~ROSLaunchManager()
    {
        if (m_running.load()) {
            m_running.store(false);

            if (m_thread.joinable()) {
                m_thread.join();
            }
        }
    }

    template<typename... Args>
    pid_t start(Args... args)
    {
        std::vector<std::string> args_vector = { args... };

        if (args_vector.size() > 0) {
            pid_t pid = ::fork();

            if (pid == 0) {
                ::setsid();

                ::signal(SIGINT, SIG_IGN);

                ::fclose(stdout);
                ::fclose(stdin);
                ::fclose(stderr);

                ::execlp("roslaunch", "roslaunch", args..., nullptr);
            }
            else {
                std::scoped_lock<std::mutex> scoped_lock(m_mutex);

                std::string args_string = std::accumulate(std::next(std::begin(args_vector)), std::end(args_vector), args_vector[0], [](std::string lhs, std::string rhs) -> std::string { return lhs + " " + rhs; });

                ROS_INFO("Starting \"roslaunch %s\" with PID %d", args_string.c_str(), pid);

                m_pids.push_back(pid);
            }

            return pid;
        }
        else {
            throw std::runtime_error("ROSLaunchManager::start - No arguments provided");
        }
    }

    void stop(pid_t const &pid, int32_t const &signal)
    {
        std::scoped_lock<std::mutex> scoped_lock(m_mutex);

        auto pid_it = std::find(std::begin(m_pids), std::end(m_pids), pid);

        if (pid_it != m_pids.end()) {
            ::kill(pid, signal);

            ROS_INFO("Stopping process with PID %d and signal %d", pid, signal);
        }
        else {
            throw std::runtime_error("ROSLaunchManager::stop - PID " + std::to_string(pid) + " not found");
        }
    }

private:
    void wait()
    {
        while (m_running.load()) {
            std::scoped_lock<std::mutex> scoped_lock(m_mutex);

            for (auto pid_it = std::begin(m_pids); pid_it != std::end(m_pids); ++pid_it) {
                pid_t const pid = *pid_it;

                int32_t status;

                if (::waitpid(pid, &status, WUNTRACED | WCONTINUED | WNOHANG) == pid) {
                    if (WIFEXITED(status)) {
                        ROS_INFO("PID %d exited with status %d", pid, WEXITSTATUS(status));

                        pid_it = m_pids.erase(pid_it);

                        if (pid_it == std::end(m_pids)) {
                            break;
                        }
                    }
                    else if (WIFSIGNALED(status)) {
                        ROS_INFO("PID %d killed with signal %d", pid, WTERMSIG(status));

                        pid_it = m_pids.erase(pid_it);

                        if (pid_it == std::end(m_pids)) {
                            break;
                        }
                    }
                    else if (WIFSTOPPED(status)) {
                        ROS_INFO("PID %d stopped with signal %d", pid, WSTOPSIG(status));
                    }
                    else if (WIFCONTINUED(status)) {
                        ROS_INFO("PID %d continued"   , pid);
                    }
                }
            }
        }

        std::scoped_lock<std::mutex> scoped_lock(m_mutex);

        for (pid_t const &pid : m_pids) {
            ::kill(pid, SIGINT);

            int32_t status;

            ::waitpid(pid, &status, 0);
        }
    }
};
</code>```

Usage:

```<code>ROSLaunchManager ros_launch_manager;
pid_t rtabmap_pid;

// Start roslaunch program

try {
    rtabmap_pid = ros_launch_manager.start(
        "rtabmap_ros", "rtabmap.launch",
        "rtabmap_args:=\"--delete_db_on_start\"",
        "depth_topic:=/camera/aligned_depth_to_color/image_raw",
        "rgb_topic:=/camera/color/image_raw",
        "camera_info_topic:=/camera/color/camera_info",
        "approx_sync:=false");
}
catch (std::exception const &exception) {
    ROS_WARN("%s", exception.what());
}

// Stop roslaunch program

try {
    ros_launch_manager.stop(rtabmap_pid, SIGINT);
}
catch (std::exception const &exception) {
    ROS_WARN("%s", exception.what());
}
</code>```

When ros_launch_manager is destroyed all of its processes are killed. The processes can be stopped/continued as well with SIGSTOP/SIGCONT.

Body:
I'm new to ROS and i'm looking for launching a 'video_stream_opencv' node programatically.

Link below :
http://wiki.ros.org/video_stream_opencv

the launch file is working well with the commands roslaunch

<group ns="$(arg camera_name)">
    <node pkg="video_stream_opencv" type="video_stream" name="$(arg camera_name)_stream" output="screen">
        <remap from="camera" to="image_raw" />
        <param name="camera_name" type="string" value="$(arg camera_name)" />
        <param name="video_stream_provider" type="string" value="$(arg video_stream_provider)" />
        <param name="fps" type="int" value="$(arg fps)" />
        <param name="frame_id" type="string" value="$(arg frame_id)" />
        <param name="camera_info_url" type="string" value="$(arg camera_info_url)" />
        <param name="flip_horizontal" type="bool" value="$(arg flip_horizontal)" />
        <param name="flip_vertical" type="bool" value="$(arg flip_vertical)" />
        <param name="width" type="int" value="$(arg width)" />
        <param name="height" type="int" value="$(arg height)" />
    </node>

    <node if="$(arg visualize)" name="$(arg camera_name)_image_view" pkg="image_view" type="image_view">
        <remap from="image" to="image_raw" />
    </node>
</group>

But now i'm trying to do the same with C++ code but i don't see how to set the 'type' attributes in my node...

printf("Started ROS thread\n");

//glutInit(&argc, argv);

ros::init(argc, argv, "camera_name);
ROS_INFO("camera_name started");

// MY params to set
std::string camera_name = "toto";
std::string video_stream_provider = "toto";
int  fps  = 30;
std::string  frame_id= "toto";
std::string  camera_info_url= "toto";
bool flip_horizontal= false;
bool flip_vertical= false;
int width = 30;
int height = 30;

ros::NodeHandle nh;
ros::M_string remappings;
remappings.insert(std::make_pair("camera", "image_raw"));
ros::NodeHandle node_handle(nh, "camera_name",remappings);

node_handle.setParam("type",video_stream);
node_handle.setParam("camera_name",camera_name);
node_handle.setParam("video_stream_provider",video_stream_provider );
node_handle.setParam("fps",fps);
node_handle.setParam("frame_id",frame_id);
node_handle.setParam("camera_info_url", camera_info_url);
node_handle.setParam("flip_horizontal", flip_horizontal);
node_handle.setParam("flip_vertical",flip_vertical);
node_handle.setParam("width", width);
node_handle.setParam("height", height);

Body:
Reviving an old thread to help those in need.

I have created a class for this purpose that is based upon "rosspawn".

ros_launch_manager.hpp:

#pragma once

#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>

#include <cstdint>
#include <memory>
#include <thread>
#include <mutex>
#include <vector>
#include <algorithm>
#include <numeric>

#include "ros/ros.h"
#include "ros/console.h"
#include "rospack/rospack.h"

class ROSLaunchManager
{
    std::vector<pid_t> m_pids;

    std::atomic<bool> m_running;
    std::thread m_thread;
    std::mutex m_mutex;

public:
    ROSLaunchManager(ROSLaunchManager const &)
    {
    }

    ROSLaunchManager()
    {
        std::atomic_init(&m_running, true);

        m_thread = std::thread(&ROSLaunchManager::wait, this);
    }

    ~ROSLaunchManager()
    {
        if (m_running.load()) {
            m_running.store(false);

            if (m_thread.joinable()) {
                m_thread.join();
            }
        }
    }

    template<typename... Args>
    pid_t start(Args... args)
    {
        std::vector<std::string> args_vector = { args... };

        if (args_vector.size() > 0) {
            pid_t pid = ::fork();

            if (pid == 0) {
                ::setsid();

                ::signal(SIGINT, SIG_IGN);

                ::fclose(stdout);
                ::fclose(stdin);
                ::fclose(stderr);

                ::execlp("roslaunch", "roslaunch", args..., nullptr);
            }
            else {
                std::scoped_lock<std::mutex> scoped_lock(m_mutex);

                std::string args_string = std::accumulate(std::next(std::begin(args_vector)), std::end(args_vector), args_vector[0], [](std::string lhs, std::string rhs) -> std::string { return lhs + " " + rhs; });

                ROS_INFO("Starting \"roslaunch %s\" with PID %d", args_string.c_str(), pid);

                m_pids.push_back(pid);
            }

            return pid;
        }
        else {
            throw std::runtime_error("ROSLaunchManager::start - No arguments provided");
        }
    }

    void stop(pid_t const &pid, int32_t const &signal)
    {
        std::scoped_lock<std::mutex> scoped_lock(m_mutex);

        auto pid_it = std::find(std::begin(m_pids), std::end(m_pids), pid);

        if (pid_it != m_pids.end()) {
            ::kill(pid, signal);

            ROS_INFO("Stopping process with PID %d and signal %d", pid, signal);
        }
        else {
            throw std::runtime_error("ROSLaunchManager::stop - PID " + std::to_string(pid) + " not found");
        }
    }

private:
    void wait()
    {
        while (m_running.load()) {
            std::scoped_lock<std::mutex> scoped_lock(m_mutex);

            for (auto pid_it = std::begin(m_pids); pid_it != std::end(m_pids); ++pid_it) {
                pid_t const pid = *pid_it;

                int32_t status;

                if (::waitpid(pid, &status, WUNTRACED | WCONTINUED | WNOHANG) == pid) {
                    if (WIFEXITED(status)) {
                        ROS_INFO("PID %d exited with status %d", pid, WEXITSTATUS(status));

                        pid_it = m_pids.erase(pid_it);

                        if (pid_it == std::end(m_pids)) {
                            break;
                        }
                    }
                    else if (WIFSIGNALED(status)) {
                        ROS_INFO("PID %d killed with signal %d", pid, WTERMSIG(status));

                        pid_it = m_pids.erase(pid_it);

                        if (pid_it == std::end(m_pids)) {
                            break;
                        }
                    }
                    else if (WIFSTOPPED(status)) {
                        ROS_INFO("PID %d stopped with signal %d", pid, WSTOPSIG(status));
                    }
                    else if (WIFCONTINUED(status)) {
                        ROS_INFO("PID %d continued"   , pid);
                    }
                }
            }
        }

        std::scoped_lock<std::mutex> scoped_lock(m_mutex);

        for (pid_t const &pid : m_pids) {
            ::kill(pid, SIGINT);

            int32_t status;

            ::waitpid(pid, &status, 0);
        }
    }
};

Usage:

ROSLaunchManager ros_launch_manager;
pid_t rtabmap_pid;

// Start roslaunch program

try {
    rtabmap_pid = ros_launch_manager.start(
        "rtabmap_ros", "rtabmap.launch",
        "rtabmap_args:=\"--delete_db_on_start\"",
        "depth_topic:=/camera/aligned_depth_to_color/image_raw",
        "rgb_topic:=/camera/color/image_raw",
        "camera_info_topic:=/camera/color/camera_info",
        "approx_sync:=false");
}
catch (std::exception const &exception) {
    ROS_WARN("%s", exception.what());
}

// Stop roslaunch program

try {
    ros_launch_manager.stop(rtabmap_pid, SIGINT);
}
catch (std::exception const &exception) {
    ROS_WARN("%s", exception.what());
}

When ros_launch_manager is destroyed all of its processes are killed. The processes can be stopped/continued as well with SIGSTOP/SIGCONT.