问:
check 10 PlayerPrefs which is Empty and Save
i coded the following code i want to check which PlayerPrefs is empty and save text from inputbox then display it in Ui text

```<code>SaveTittlesText1.text=PlayerPrefs.GetString("1");
SaveTittlesText2.text=PlayerPrefs.GetString("2");
SaveTittlesText3.text=PlayerPrefs.GetString("3")
</code>```

problem is Uitext3 is displaying text from Uitex2 please help i want to achieve this in more than 10 PlayerPrefs

```<code>if (PlayerPrefs.HasKey ("1") == false)
{
    PlayerPrefs.SetString("1",InputsaveTittes.text.ToString());

    PlayerPrefs.Save();
}
else if (PlayerPrefs.HasKey ("1") == true)
{
    PlayerPrefs.SetString("2",InputsaveTittes.text.ToString());

    PlayerPrefs.Save();
}
else if (PlayerPrefs.HasKey ("2") == false)
{
    PlayerPrefs.SetString("2",InputsaveTittes.text.ToString());

     PlayerPrefs.Save();
}
else if (PlayerPrefs.HasKey ("2") == true)
{
    PlayerPrefs.SetString("3",InputsaveTittes.text.ToString());

    PlayerPrefs.Save();
}

</code>```

答:
I don't really understand that use case / logic but you are skipping a case:

```<code>if (PlayerPrefs.HasKey ("1") == false)
{
    // sets 1
}
else if (PlayerPrefs.HasKey("1") == true) // WHAT IF IT ALSO PlayerPrefs.HasKey ("2") == true here ?
{
    // sets 2
}
else if (PlayerPrefs.HasKey ("2") == false) // WILL NEVER BE REACHED
{
    // sets 2
}
else if (PlayerPrefs.HasKey ("2") == true) // WILL NEVER BE REACHED
{
    // sets 3
}
</code>```

your last two cases will never be reached/checked at all since your first two cases already cover all possibilities!

you should either check like e.g.

```<code>if (!PlayerPrefs.HasKey ("1"))
{
    PlayerPrefs.SetString("1", InputsaveTittes.text);
}
// already know that 1 is set since otherwise it would have entered the first case
else if (!PlayerPrefs.HasKey ("2"))
{
    PlayerPrefs.SetString("2", InputsaveTittes.text);
}
// Any other case -> this means 1 and 2 are already set
else
{
    PlayerPrefs.SetString("3", InputsaveTittes.text);
}

PlayerPrefs.Save();
</code>```

or in general use loops!

```<code>// iterate over 1,2,3
for(var i = 1; i <= 3; i++)
{
    // check if current index is already used
    if(!PlayerPrefs.HasKey(i))
    {
        // if not set it
        PlayerPrefs.SetString(i.ToString(), InputsaveTittes.text);
        PlayerPrefs.Save();

        // skip the rest of the loop
        break;
    }
}
</code>```

Actually I would however rather simply have another entry for storing the current index -  especially if you are going for more items - like e.g.

```<code>// defaults to 0 if there is no index yet -> first player will have index 1
var index = PlayerPrefs.GetInt("index", 0);
// increase index by 1
index++;
// store string to this new index
PlayerPrefs.SetString(index.ToString(), InputsaveTittes.text);
// also store the new index
PlayerPrefs.SetInt("index", index);
PlayerPrefs.Save();
</code>```

at the same time PlayerPrefs.GetInt("index", 0); will now also return the amount of already saved strings.

problem is Uitext3 is displaying text from Uitex2

This, however, sounds like you simply referenced the same Text component in both fields SaveTittlesText2 and SaveTittlesText3.

Body:
i coded the following code i want to check which PlayerPrefs is empty and save text from inputbox then display it in Ui text

SaveTittlesText1.text=PlayerPrefs.GetString("1");
SaveTittlesText2.text=PlayerPrefs.GetString("2");
SaveTittlesText3.text=PlayerPrefs.GetString("3")

problem is Uitext3 is displaying text from Uitex2 please help i want to achieve this in more than 10 PlayerPrefs

if (PlayerPrefs.HasKey ("1") == false)
{
    PlayerPrefs.SetString("1",InputsaveTittes.text.ToString());

    PlayerPrefs.Save();
}
else if (PlayerPrefs.HasKey ("1") == true)
{
    PlayerPrefs.SetString("2",InputsaveTittes.text.ToString());

    PlayerPrefs.Save();
}
else if (PlayerPrefs.HasKey ("2") == false)
{
    PlayerPrefs.SetString("2",InputsaveTittes.text.ToString());

     PlayerPrefs.Save();
}
else if (PlayerPrefs.HasKey ("2") == true)
{
    PlayerPrefs.SetString("3",InputsaveTittes.text.ToString());

    PlayerPrefs.Save();
}

Body:
I don't really understand that use case / logic but you are skipping a case:

if (PlayerPrefs.HasKey ("1") == false)
{
    // sets 1
}
else if (PlayerPrefs.HasKey("1") == true) // WHAT IF IT ALSO PlayerPrefs.HasKey ("2") == true here ?
{
    // sets 2
}
else if (PlayerPrefs.HasKey ("2") == false) // WILL NEVER BE REACHED
{
    // sets 2
}
else if (PlayerPrefs.HasKey ("2") == true) // WILL NEVER BE REACHED
{
    // sets 3
}

your last two cases will never be reached/checked at all since your first two cases already cover all possibilities!

you should either check like e.g.

if (!PlayerPrefs.HasKey ("1"))
{
    PlayerPrefs.SetString("1", InputsaveTittes.text);
}
// already know that 1 is set since otherwise it would have entered the first case
else if (!PlayerPrefs.HasKey ("2"))
{
    PlayerPrefs.SetString("2", InputsaveTittes.text);
}
// Any other case -> this means 1 and 2 are already set
else
{
    PlayerPrefs.SetString("3", InputsaveTittes.text);
}

PlayerPrefs.Save();

or in general use loops!

// iterate over 1,2,3
for(var i = 1; i <= 3; i++)
{
    // check if current index is already used
    if(!PlayerPrefs.HasKey(i))
    {
        // if not set it
        PlayerPrefs.SetString(i.ToString(), InputsaveTittes.text);
        PlayerPrefs.Save();

        // skip the rest of the loop
        break;
    }
}

Actually I would however rather simply have another entry for storing the current index -  especially if you are going for more items - like e.g.

// defaults to 0 if there is no index yet -> first player will have index 1
var index = PlayerPrefs.GetInt("index", 0);
// increase index by 1
index++;
// store string to this new index
PlayerPrefs.SetString(index.ToString(), InputsaveTittes.text);
// also store the new index
PlayerPrefs.SetInt("index", index);
PlayerPrefs.Save();

at the same time PlayerPrefs.GetInt("index", 0); will now also return the amount of already saved strings.

problem is Uitext3 is displaying text from Uitex2

This, however, sounds like you simply referenced the same Text component in both fields SaveTittlesText2 and SaveTittlesText3.


来源: stackexchange

问:
Make camera fill full screen
I've got a kivy app and I'd like to make the camera component fill the entire screen as the background. Here's what I've currently got:

```<code><CamBoxLayout>:
    orientation: "vertical"
    display: entry
    padding: 10
    spacing: 10

    BoxLayout:
        size_hint: 1, 1
        id: entry
        multiline: False
        Camera:
            center: self.size and entry.center
            size: entry.height, entry.width

            canvas.before:
                PushMatrix:
                Rotate:
                    angle: 90
                    origin: self.center

            canvas.after:
                PopMatrix:
            allow_stretch: True
            resolution: (720, 1080)
            play: True
</code>```

but the camera just fills part of the screen, it hides behind any button though, so that's good.
Thanks, Ed.

答:
```<code>allow_stretch: True
keep_ratio:False
</code>```

Add these codes to Camera properties.

ContentLicense: CC BY-SA 3.0

Title: Make camera fill full screen

Body:
I've got a kivy app and I'd like to make the camera component fill the entire screen as the background. Here's what I've currently got:

<CamBoxLayout>:
    orientation: "vertical"
    display: entry
    padding: 10
    spacing: 10

    BoxLayout:
        size_hint: 1, 1
        id: entry
        multiline: False
        Camera:
            center: self.size and entry.center
            size: entry.height, entry.width

            canvas.before:
                PushMatrix:
                Rotate:
                    angle: 90
                    origin: self.center

            canvas.after:
                PopMatrix:
            allow_stretch: True
            resolution: (720, 1080)
            play: True

but the camera just fills part of the screen, it hides behind any button though, so that's good.
Thanks, Ed.

Body:
allow_stretch: True
keep_ratio:False

Add these codes to Camera properties.

ContentLicense: CC BY-SA 4.0


问:
How to add a global state store in a Spring Cloud Stream application
I'm trying to configure a global state store in a Spring Cloud Stream application but it fails with :

Exception in thread "svc-toa-app-datainteg-io-dev-fd2e1a47-0758-4b95-9b2e-022ca4df95ca-
StreamThread-1" org.apache.kafka.streams.errors.TopologyException: Invalid topology:
Topic is unknown to the topology. This may happen if different KafkaStreams instances of
the same application execute different Topologies. Note that Topologies are only identical if all operators are added in the same order.

Following the official documentation I added the following to configure the state store :

 @Bean
    public StreamsBuilderFactoryBeanCustomizer streamsBuilderFactoryBeanCustomizer() {
        return factoryBean -> {
            if (factoryBean.getStreamsConfiguration().getProperty(StreamsConfig.APPLICATION_ID_CONFIG)
                           .equals(applicationId)) {
                try {

                    final var keyValueStore = new KeyValueStoreBuilder<>(
                        Stores.inMemoryKeyValueStore(PRODUCT_INFO_STORE),
                        productInfoKeySerde(),
                        productInfoValueSerde(),
                        Time.SYSTEM
                    );

                    final StreamsBuilder streamsBuilder = factoryBean.getObject();

                    streamsBuilder.addGlobalStore(
                        keyValueStore.withLoggingDisabled(),
                        productInfoTopic,
                        Consumed.with(productInfoKeySerde(), productInfoValueSerde()),
                        ProductGlobalStateStoreProcessor::new
                    );
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
    }
```
<p>And I have a processor where I want to use the state store :</p>
<pre class="lang-java prettyprint-override"><code>public class ProductGlobalStateStoreProcessor implements Processor<ProductInfoKey, ProductInfo, Void, Void> {
    KeyValueStore<ProductInfoKey, ProductInfo> stateStore;

    @Override
    public void init(ProcessorContext<Void, Void> context) {
        stateStore = context.getStateStore(ProductGlobalStateStoreConfiguration.PRODUCT_INFO_STORE);
    }

    @Override
    public void process(Record<ProductInfoKey, ProductInfo> record) {
        stateStore.put(record.key(), record.value());
    }
}
</code>```

I'm a little lost on what I'm missing, I've tried to add a gktable binding in the properties but it does not change anything.

答:
I've found my issue : another instance was running with the same application id.

Since I added a new source node for the global state store, topologies were different and that's why it would not start.

Body:
I'm trying to configure a global state store in a Spring Cloud Stream application but it fails with :

Exception in thread "svc-toa-app-datainteg-io-dev-fd2e1a47-0758-4b95-9b2e-022ca4df95ca-
StreamThread-1" org.apache.kafka.streams.errors.TopologyException: Invalid topology:
Topic is unknown to the topology. This may happen if different KafkaStreams instances of
the same application execute different Topologies. Note that Topologies are only identical if all operators are added in the same order.

Following the official documentation I added the following to configure the state store :

 @Bean
    public StreamsBuilderFactoryBeanCustomizer streamsBuilderFactoryBeanCustomizer() {
        return factoryBean -> {
            if (factoryBean.getStreamsConfiguration().getProperty(StreamsConfig.APPLICATION_ID_CONFIG)
                           .equals(applicationId)) {
                try {

                    final var keyValueStore = new KeyValueStoreBuilder<>(
                        Stores.inMemoryKeyValueStore(PRODUCT_INFO_STORE),
                        productInfoKeySerde(),
                        productInfoValueSerde(),
                        Time.SYSTEM
                    );

                    final StreamsBuilder streamsBuilder = factoryBean.getObject();

                    streamsBuilder.addGlobalStore(
                        keyValueStore.withLoggingDisabled(),
                        productInfoTopic,
                        Consumed.with(productInfoKeySerde(), productInfoValueSerde()),
                        ProductGlobalStateStoreProcessor::new
                    );
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
    }

And I have a processor where I want to use the state store :

public class ProductGlobalStateStoreProcessor implements Processor<ProductInfoKey, ProductInfo, Void, Void> {
    KeyValueStore<ProductInfoKey, ProductInfo> stateStore;

    @Override
    public void init(ProcessorContext<Void, Void> context) {
        stateStore = context.getStateStore(ProductGlobalStateStoreConfiguration.PRODUCT_INFO_STORE);
    }

    @Override
    public void process(Record<ProductInfoKey, ProductInfo> record) {
        stateStore.put(record.key(), record.value());
    }
}

I'm a little lost on what I'm missing, I've tried to add a gktable binding in the properties but it does not change anything.


问:
Help me my first test
I have created a Hello World program and I am new to C#, My program will print 100 words like that as follow

```<code>public static void Main(/*I forgot arguments*/)
{
   string []s=new string [100];
   foreach(string ss in s)
   {
      ss="Hello World";
      Console.WriteLine("{0}\n",ss);
   }
}
</code>```

Could you show me  step-by-step how to create a test for this program ? Does it need one ? I don't have an image of how testers do the test. Sorry I am stupid.

I think I have tried my best, no one ever find I find it unworthy to me not to get any help ? I don't need the class because I forgot the class long ago after the accident.

答: Flush the above code to a method than having it in the main. Then refer to some unit test cases documents (If unit testing is what your looking for) here http://www.nunit.org/index.php?p=quickStart&r=2.5.10</p>

Title: Help me my first test

Body:
I have created a Hello World program and I am new to C#, My program will print 100 words like that as follow

public static void Main(/*I forgot arguments*/)
{
   string []s=new string [100];
   foreach(string ss in s)
   {
      ss="Hello World";
      Console.WriteLine("{0}\n",ss);
   }
}

Could you show me  step-by-step how to create a test for this program ? Does it need one ? I don't have an image of how testers do the test. Sorry I am stupid.

I think I have tried my best, no one ever find I find it unworthy to me not to get any help ? I don't need the class because I forgot the class long ago after the accident.


问:
How registerForActivityResult in android handles multiple requests?
Android onActivityResult is Deprecated.

But I am trying to build an App in Java with a button which will give two option to select photo , either through gallery or through Camera. In onActivityResult, it used to have request codes. So earlier we can get two different request codes for camera and gallery and according using if statement we can handle them using onActivityResult. Now how should we implement it ?

Below is the older way which I mentioned:

''''

```<code>@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode == CAPTURE_IMAGE){

        if(resultCode == RESULT_OK){

            if(mImageUri != null){

                //REST OF CODE

            }

        }

    }

    if(requestCode == GALLARY_PICK){

        if(resultCode == RESULT_OK){

            Uri uri = data.getData();
            if(uri != null) {

                 //REST OF CODE

            }

        }

    }

}
</code>```

''''

答:
From the documentation:

The Activity Result APIs provide components for registering for a
result, launching the result, and handling the result once it is
dispatched by the system.

Also, you can read here why they deprecated the onActivityResult() callback.

When starting an activity for a result, it is possible (and, in cases
of memory-intensive operations such as camera usage, almost certain)
that your process and your activity will be destroyed due to low
memory.

For this reason, the Activity Result APIs decouple the result callback
from the place in your code where you launch the other activity. As
the result callback needs to be available when your process and
activity are recreated, the callback must be unconditionally
registered every time your activity is created, even if the logic of
launching the other activity only happens based on user input or other
business logic.

For camera, use Take Picture contract

For Gallery, use Get Content contract

Update:

You can create your custom contract something like this:

```<code>class DsPhotoEditorContract : ActivityResultContract<Uri, Uri?>() {
    override fun createIntent(context: Context, input: Uri) =
        Intent(context, DsPhotoEditorActivity::class).apply {
            data = input
            putExtra(DsPhotoEditorConstants.DS_PHOTO_EDITOR_OUTPUT_DIRECTORY, "YOUR_OUTPUT_IMAGE_FOLDER")
        }

    override fun parseResult(resultCode: Int, intent: Intent?) : Uri? {
        if (resultCode != Activity.RESULT_OK) {
            return null
        }
        return intent?.data;
    }
}
</code>```

Body:
Android onActivityResult is Deprecated.

But I am trying to build an App in Java with a button which will give two option to select photo , either through gallery or through Camera. In onActivityResult, it used to have request codes. So earlier we can get two different request codes for camera and gallery and according using if statement we can handle them using onActivityResult. Now how should we implement it ?

Below is the older way which I mentioned:

''''

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode == CAPTURE_IMAGE){

        if(resultCode == RESULT_OK){

            if(mImageUri != null){

                //REST OF CODE

            }

        }

    }

    if(requestCode == GALLARY_PICK){

        if(resultCode == RESULT_OK){

            Uri uri = data.getData();
            if(uri != null) {

                 //REST OF CODE

            }

        }

    }

}

''''

Body:
From the documentation:

The Activity Result APIs provide components for registering for a
result, launching the result, and handling the result once it is
dispatched by the system.

Also, you can read here why they deprecated the onActivityResult() callback.

When starting an activity for a result, it is possible (and, in cases
of memory-intensive operations such as camera usage, almost certain)
that your process and your activity will be destroyed due to low
memory.

For this reason, the Activity Result APIs decouple the result callback
from the place in your code where you launch the other activity. As
the result callback needs to be available when your process and
activity are recreated, the callback must be unconditionally
registered every time your activity is created, even if the logic of
launching the other activity only happens based on user input or other
business logic.

For camera, use Take Picture contract

For Gallery, use Get Content contract

Update:

You can create your custom contract something like this:

class DsPhotoEditorContract : ActivityResultContract<Uri, Uri?>() {
    override fun createIntent(context: Context, input: Uri) =
        Intent(context, DsPhotoEditorActivity::class).apply {
            data = input
            putExtra(DsPhotoEditorConstants.DS_PHOTO_EDITOR_OUTPUT_DIRECTORY, "YOUR_OUTPUT_IMAGE_FOLDER")
        }

    override fun parseResult(resultCode: Int, intent: Intent?) : Uri? {
        if (resultCode != Activity.RESULT_OK) {
            return null
        }
        return intent?.data;
    }
}


问:
Navbar overshadows/overlaps the content of a page
So I am learning HTMl/css and I came across this issue:

Wide screen; nav bar covers the content

Smaller screen; nav bar covers the content even more

Here is some sampple code to reproduce this problem:

```<code><!DOCTYPE html>
<html>
<head>
<style>
body {margin:0;}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
  position: fixed;
  top: 0;
  width: 100%;
}

li {
  float: left;
}

li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover:not(.active) {
  background-color: #111;
}

.active {
  background-color: #04AA6D;
}
</style>
</head>
<body>

<ul>
  <li><a class="active" href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li><a class="active" href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li><a class="active" href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li><a class="active" href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li><a class="active" href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li><a class="active" href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li><a class="active" href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li><a class="active" href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li><a class="active" href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
</ul>

<div style="padding:20px;margin-top:30px;background-color:#1abc9c;height:1500px;">
  <h1>Fixed Top Navigation Bar</h1>
  <h2>Scroll this page to see the effect</h2>
  <h2>The navigation bar will stay at the top of the page while scrolling</h2>

  <p>Some text some text some text some text..</p>
</div>

</body>
</html>
</code>```

My question is, does anyone know how to make everything underneath the nav bar, go UNDER the nav bar? So that the nav bar wont cover the contents?

Thanks in advance!

答:
body {
  margin: 0;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
  /*position: fixed;*/
  top: 0;
  width: 100%;
}

li {
  float: left;
}

li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover:not(.active) {
  background-color: #111;
}

.active {
  background-color: #04AA6D;
}

body {
  margin: 0;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
  /*position: fixed;*/
  top: 0;
  width: 100%;
}

li {
  float: left;
}

li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover:not(.active) {
  background-color: #111;
}

.active {
  background-color: #04AA6D;
}
.divb{
/*margin-top:30px;*/
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>Home</li>
  <li>News</li>
  <li>Contact</li>
  <li>About</li>
  <li>Home</li>
  <li>News</li>
  <li>Contact</li>
  <li>About</li>
  <li>Home</li>
  <li>News</li>
  <li>Contact</li>
  <li>About</li>
  <li>Home</li>
  <li>News</li>
  <li>Contact</li>
  <li>About</li>
  <li>Home</li>
  <li>News</li>
  <li>Contact</li>
  <li>About</li>
  <li>Home</li>
  <li>News</li>
  <li>Contact</li>
  <li>About</li>
  <li>Home</li>
  <li>News</li>
  <li>Contact</li>
  <li>About</li>
  <li>Home</li>
  <li>News</li>
  <li>Contact</li>
  <li>About</li>
  <li>Home</li>
  <li>News</li>
  <li>Contact</li>
  <li>About</li>
</ul>

<div style="padding:20px;background-color:#1abc9c;height:1500px;" class="divb">
  <h1>Fixed Top Navigation Bar</h1>
  <h2>Scroll this page to see the effect</h2>
  <h2>The navigation bar will stay at the top of the page while scrolling</h2>

  <p>This answer prevents it!</p>
</div></code>```

Simply remove position: fixed; i have comented them

Body:
So I am learning HTMl/css and I came across this issue:

Wide screen; nav bar covers the content

Smaller screen; nav bar covers the content even more

Here is some sampple code to reproduce this problem:

<!DOCTYPE html>

Home

News

Contact

About

Home

News

Contact

About

Home

News

Contact

About

Home

News

Contact

About

Home

News

Contact

About

Home

News

Contact

About

Home

News

Contact

About

Home

News

Contact

About

Home

News

Contact

About

Fixed Top Navigation Bar

Scroll this page to see the effect

The navigation bar will stay at the top of the page while scrolling

Some text some text some text some text..

My question is, does anyone know how to make everything underneath the nav bar, go UNDER the nav bar? So that the nav bar wont cover the contents?

Thanks in advance!

Body:
body {
  margin: 0;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
  /*position: fixed;*/
  top: 0;
  width: 100%;
}

li {
  float: left;
}

li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover:not(.active) {
  background-color: #111;
}

.active {
  background-color: #04AA6D;
}

body {
  margin: 0;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
  /*position: fixed;*/
  top: 0;
  width: 100%;
}

li {
  float: left;
}

li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover:not(.active) {
  background-color: #111;
}

.active {
  background-color: #04AA6D;
}
.divb{
/*margin-top:30px;*/
}

<ul>
  <li><a class="active" href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li><a class="active" href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li><a class="active" href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li><a class="active" href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li><a class="active" href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li><a class="active" href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li><a class="active" href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li><a class="active" href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li><a class="active" href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
</ul>

<div style="padding:20px;background-color:#1abc9c;height:1500px;" class="divb">
  <h1>Fixed Top Navigation Bar</h1>
  <h2>Scroll this page to see the effect</h2>
  <h2>The navigation bar will stay at the top of the page while scrolling</h2>

  <p>This answer prevents it!</p>
</div>

Simply remove position: fixed; i have comented them


问:
How to programmatically validate Tether (TRC20) Wallet Addresses in PHP?
I am having an issue related to validating cryptocurrency wallet addresses, specifically USDT.

USDT can be validated either as a BTC or ETH address, depending on the network type.

Basically it goes like that:

If cryptocurrency is USDT and chain type is ERC20, validate the address against ETH
address format.

If cryptocurrency is USDT and wallet type is OMNI, validate the address against BTC
address format.

I haven't managed to find a specific validation for USDT:TRC20 addresses and I am not sure how to validate them.

答:
Regex for matching Tron address:
T[A-Za-z1-9]{33}


问:
Next js scroll event not calling on scroll?
```<code>  useEffect(() => {

        document.addEventListener("scroll",  ()=> {
              console.log('.................gotcha');

          });

     },[]);
</code>```

I am wanting to fire an event when user is scrolling. I have used the above code to get the scroll event. But its not working. But the same code is working on another project

whole code

```<code>import Image from 'next/image';
import React, { useEffect, useRef,  } from 'react';
import { useCallback } from 'react';
import { useState } from 'react';
import { Container } from "react-bootstrap";
import hostname from '../../lib/config';
import styles from './LandingPage.module.css';

function LandingPage({settings}) {

    useEffect(() => {

        document.addEventListener("scroll",  ()=> {
              console.log('.................gotcha');

          });

     },[]);

    return (
        <div>
            <div style={{textAlign: 'center'}} className={styles.margin__top}>
                <Image src={`${hostname}/${settings?.top?.image}`} height={850} width={2100} />
                <div className={styles.top__image__text}>
                    <h1 style={{textAlign: 'center'}}>{settings?.top?.firstText}</h1>
                    <h3 style={{textAlign: 'center'}}>{settings?.top?.secondText}</h3>
                    <p style={{textAlign: 'center'}}>{settings?.top?.thirdText}</p>
                </div>
                {/* <div className="text-center" style={{marginTop: '-256px'}}><Image src="/assets/images/landingPage/2.png" height={250} width={500} /></div> */}
            </div>
            <Container>
                <div className={styles.two__container__style}>
                    <div>
                        <Image src={`${hostname}/${settings?.top?.firstSection?.image}`} height={350} width={450} />
                    </div>
                    <div className={styles.content__style}>
                        <div dangerouslySetInnerHTML={{__html: `${settings?.firstSection?.text}`}} />
                        {/* <h2>Secure access, worldwide</h2>
                        <p>Connect reliably from anywhere, to anywhere. Our network of high-speed servers across 94 countries puts you in control.</p> */}
                        <button>Get Red Card VPN</button>
                    </div>
                    <div className={styles.content__style}>
                        <div dangerouslySetInnerHTML={{__html: `${settings?.secondSection?.text}`}} />

                    </div>
                    <div>
                        <Image src={`${hostname}/${settings?.secondSection?.image}`} height={350} width={450} />
                    </div>
                </div>
                <div className={styles.three__container__style}>
                    <div className={styles.mini__container__style}>
                        <Image src={`${hostname}/${settings?.thirdSection?.firstImage}`} height={120} width={200} className={styles.image__radius} />
                        <div dangerouslySetInnerHTML={{__html: `${settings?.thirdSection?.firstText}`}} />

                    </div>
                    <div className={styles.mini__container__style}>
                        <Image src={`${hostname}/${settings?.thirdSection?.secondImage}`} height={120} width={200} className={styles.image__radius} />
                        <div dangerouslySetInnerHTML={{__html: `${settings?.thirdSection?.secondText}`}} />

                    </div>
                    <div className={styles.mini__container__style}>
                        <Image src={`${hostname}/${settings?.thirdSection?.thirdImage}`} height={120} width={200} className={styles.image__radius} />
                        <div dangerouslySetInnerHTML={{__html: `${settings?.thirdSection?.thirdText}`}} />

                    </div>
                </div>
            </Container>
        </div>
    );
}

export default LandingPage;
</code>```

答:
As per your shared code, I had tried them in a new project with normal div instead of Container, my own CSS styles and hostname (as it is not shared in the post) and it is working fine. so please try below two options.

Try to replace Container with normal div and check

As mentioned by you that it is working fine in another project, So please check your global CSS and LandingPage.module.css there must be some CSS which is not allowing to scroll, you can test by removing both the CSS and check

Body:
  useEffect(() => {

        document.addEventListener("scroll",  ()=> {
              console.log('.................gotcha');

          });

     },[]);

I am wanting to fire an event when user is scrolling. I have used the above code to get the scroll event. But its not working. But the same code is working on another project

whole code

import Image from 'next/image';
import React, { useEffect, useRef,  } from 'react';
import { useCallback } from 'react';
import { useState } from 'react';
import { Container } from "react-bootstrap";
import hostname from '../../lib/config';
import styles from './LandingPage.module.css';

function LandingPage({settings}) {

    useEffect(() => {

        document.addEventListener("scroll",  ()=> {
              console.log('.................gotcha');

          });

     },[]);

    return (

                <Image src={`${hostname}/${settings?.top?.image}`} height={850} width={2100} />

{settings?.top?.firstText}

{settings?.top?.secondText}

{settings?.top?.thirdText}

                {/*
<Image src="/assets/images/landingPage/2.png" height={250} width={500} />
 */}

            <Container>

                        <Image src={`${hostname}/${settings?.top?.firstSection?.image}`} height={350} width={450} />

                        <div dangerouslySetInnerHTML={{__html: `${settings?.firstSection?.text}`}} />
                        {/*
Secure access, worldwide

Connect reliably from anywhere, to anywhere. Our network of high-speed servers across 94 countries puts you in control.
 */}
                        <button>Get Red Card VPN</button>

                        <div dangerouslySetInnerHTML={{__html: `${settings?.secondSection?.text}`}} />

                        <Image src={`${hostname}/${settings?.secondSection?.image}`} height={350} width={450} />

                        <Image src={`${hostname}/${settings?.thirdSection?.firstImage}`} height={120} width={200} className={styles.image__radius} />
                        <div dangerouslySetInnerHTML={{__html: `${settings?.thirdSection?.firstText}`}} />

                        <Image src={`${hostname}/${settings?.thirdSection?.secondImage}`} height={120} width={200} className={styles.image__radius} />
                        <div dangerouslySetInnerHTML={{__html: `${settings?.thirdSection?.secondText}`}} />

                        <Image src={`${hostname}/${settings?.thirdSection?.thirdImage}`} height={120} width={200} className={styles.image__radius} />
                        <div dangerouslySetInnerHTML={{__html: `${settings?.thirdSection?.thirdText}`}} />

            </Container>

    );
}

export default LandingPage;


问:
As seen in the image, create two responsive DIVs with space between them

I'm working on a codewell challenge and I'm stuck on this portion. I can't make an even space between them, and the images are overlapping.

.website {
  display: flex;
  justify-content: space-between;
}

.arrow {
  display: inline-block;
  width: 1rem;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="website">
  <div class="spense">
    <img id="spense" src="./Assets/Spense.png" alt="spense">
    <h3>Spense.com<img class="arrow" src="./Assets/noun-arrow-2841221-svg.png" alt="arrow-icon"></h3>
    Rethinking the way writers get paid, an open resource platform <br> design to help writers focus more on writing, and less on <br> when and how they'll get paid, Projects in collaboration with <br> Codewell.cc
  </div>
  <div class="yelp">
    <img id="yelp" src="./Assets/YelpCamp.png" alt="YelpCamp">
    <h3>YelpCamp.com<img class="arrow" src="./Assets/noun-arrow-2841221-svg.png" alt="arrow-icon"></h3>
    Allowing backpack travelers to perfectly plan their trip <br> through an open-source platform similar to TripAdvisor. With <br>over 1m MAU, YelpCamp has been the crowd's favorite in <br>2021.
  </div>
</div></code>```

答:
You should specify a width for divs:

.website {
  display: flex;
  justify-content: space-around;
}

.arrow {
  display: inline-block;
  width: 1rem;
}
#spense,#yelp{
  width: 100%;
}
.spense,.yelp{
   width: 30%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="website">
  <div class="spense">
    <img id="spense" src="https://s4.uupload.ir/files/1-6-5_ssnb.jpg" alt="spense">
    <h3>Spense.com<img class="arrow" src="./Assets/noun-arrow-2841221-svg.png" alt="arrow-icon"></h3>
    Rethinking the way writers get paid, an open resource platform <br> design to help writers focus more on writing, and less on <br> when and how they'll get paid, Projects in collaboration with <br> Codewell.cc
  </div>
  <div class="yelp">
    <img id="yelp" src="https://s4.uupload.ir/files/1-6-5_ssnb.jpg" alt="YelpCamp">
    <h3>YelpCamp.com<img class="arrow" src="./Assets/noun-arrow-2841221-svg.png" alt="arrow-icon"></h3>
    Allowing backpack travelers to perfectly plan their trip <br> through an open-source platform similar to TripAdvisor. With <br>over 1m MAU, YelpCamp has been the crowd's favorite in <br>2021.
  </div>
</div></code>```

Body:
I'm working on a codewell challenge and I'm stuck on this portion. I can't make an even space between them, and the images are overlapping.

.website {
  display: flex;
  justify-content: space-between;
}

.arrow {
  display: inline-block;
  width: 1rem;
}

Spense.com

    Rethinking the way writers get paid, an open resource platform
 design to help writers focus more on writing, and less on
 when and how they'll get paid, Projects in collaboration with
 Codewell.cc

YelpCamp.com

    Allowing backpack travelers to perfectly plan their trip
 through an open-source platform similar to TripAdvisor. With
over 1m MAU, YelpCamp has been the crowd's favorite in
2021.

Body:
You should specify a width for divs:

.website {
  display: flex;
  justify-content: space-around;
}

.arrow {
  display: inline-block;
  width: 1rem;
}
#spense,#yelp{
  width: 100%;
}
.spense,.yelp{
   width: 30%;
}

<div class="website">
  <div class="spense">
    <img id="spense" src="https://s4.uupload.ir/files/1-6-5_ssnb.jpg" alt="spense">
    <h3>Spense.com<img class="arrow" src="./Assets/noun-arrow-2841221-svg.png" alt="arrow-icon"></h3>
    Rethinking the way writers get paid, an open resource platform <br> design to help writers focus more on writing, and less on <br> when and how they'll get paid, Projects in collaboration with <br> Codewell.cc
  </div>
  <div class="yelp">
    <img id="yelp" src="https://s4.uupload.ir/files/1-6-5_ssnb.jpg" alt="YelpCamp">
    <h3>YelpCamp.com<img class="arrow" src="./Assets/noun-arrow-2841221-svg.png" alt="arrow-icon"></h3>
    Allowing backpack travelers to perfectly plan their trip <br> through an open-source platform similar to TripAdvisor. With <br>over 1m MAU, YelpCamp has been the crowd's favorite in <br>2021.
  </div>
</div>


问:
python regex text extraction
the text input is something like this
West Team 4, Eastern 3\n

-------Update--------

the input is a txt file containing team name and scores like a football game
the whole text file will be something like this, two names and scores:

```<code>West Team 4, Eastern 5
Nott Team 2, Eastern 3
West wood 1, Eathan 2
West Team 4, Eas 5
</code>```

I am using with open to read file line by line therefore there will be \n at the end of the line.

I would like to extract this line of text in to something like:

```<code>['West Team', 'Eastern']
</code>```

What I currently have in mind is to use regex

```<code>result = re.sub("[\n^\s$\d]", "", text).split(",")
</code>```

this code results in this:

```<code>['WestTeam','Eastern']
</code>```

I'm sure that my regex is not correct. I want to remove '\n' and any number including the space in front of the number but not the space in the middle of the name.

Open to any suggestion that to achieve this result, doesn't necessarily use regex.

答:
You haven't clearly defined the rules for getting the required output from your sample input. However, this will give what you've asked for but may not cover all eventualities:

```<code>in_string = 'West Team 4, Eastern 3\n'

result = [' '.join(t.split()[:-1]) for t in in_string.split(',')]

print(result)
</code>```

Output:

```<code>['West Team', 'Eastern']
</code>```

Title: python regex text extraction

Body:
the text input is something like this
West Team 4, Eastern 3\n

-------Update--------

the input is a txt file containing team name and scores like a football game
the whole text file will be something like this, two names and scores:

West Team 4, Eastern 5
Nott Team 2, Eastern 3
West wood 1, Eathan 2
West Team 4, Eas 5

I am using with open to read file line by line therefore there will be \n at the end of the line.

I would like to extract this line of text in to something like:

['West Team', 'Eastern']

What I currently have in mind is to use regex

result = re.sub("[\n^\s$\d]", "", text).split(",")

this code results in this:

['WestTeam','Eastern']

I'm sure that my regex is not correct. I want to remove '\n' and any number including the space in front of the number but not the space in the middle of the name.

Open to any suggestion that to achieve this result, doesn't necessarily use regex.

Body:
You haven't clearly defined the rules for getting the required output from your sample input. However, this will give what you've asked for but may not cover all eventualities:

in_string = 'West Team 4, Eastern 3\n'

result = [' '.join(t.split()[:-1]) for t in in_string.split(',')]

print(result)

Output:

['West Team', 'Eastern']


问:
subtract 2 colums from each other
I need to make a new column PRICE minus MEAN_PRICE_DISTRICT. I have tried this, but it does not work? how to subtract 2 columns from each other, my idea was probably too simple :-)

```<code>tekoopl %>%  group_by(DISTRICT)%>%  mutate(new_column= PRICE - MEAN_PRICE_DISTRICT)
</code>```

I have only just started with R ;-)
(I am currently using the packages dplyr and tidyr)

```<code>A tibble: 19,073,620 x 17
# Groups:   PRICE [24,547]
   ID          PRICE DATE  POSTCODE TYPE  OLD_NEW DURATION PAON  SAON  STREET LOCALITY TOWN  DISTRICT COUNTY PPD   STATUS
   <chr>       <int> <chr> <chr>    <chr> <chr>   <chr>    <chr> <chr> <chr>  <chr>    <chr> <chr>    <chr>  <chr> <chr>
 1 {CCA5ACA8~ 562500 2014~ SE1 0FT  F     Y       L        ROSL~ APAR~ EWER ~ NA       LOND~ SOUTHWA~ GREAT~ A     A
 2 {CCA5ACA8~ 562500 2014~ SE1 0FT  F     Y       L        ROSL~ APAR~ EWER ~ NA       LOND~ SOUTHWA~ GREAT~ A     A
 3 {CCA5ACA8~ 562500 2014~ SE1 0FT  F     Y       L        ROSL~ APAR~ EWER ~ NA       LOND~ SOUTHWA~ GREAT~ A     A
 4 {CCA5ACA8~ 562500 2014~ SE1 0FT  F     Y       L        ROSL~ APAR~ EWER ~ NA       LOND~ SOUTHWA~ GREAT~ A     A
 5 {CCA5ACA8~ 562500 2014~ SE1 0FT  F     Y       L        ROSL~ APAR~ EWER ~ NA       LOND~ SOUTHWA~ GREAT~ A     A
 6 {CCA5ACA8~ 562500 2014~ SE1 0FT  F     Y       L        ROSL~ APAR~ EWER ~ NA       LOND~ SOUTHWA~ GREAT~ A     A
 7 {CCA5ACA8~ 562500 2014~ SE1 0FT  F     Y       L        ROSL~ APAR~ EWER ~ NA       LOND~ SOUTHWA~ GREAT~ A     A
 8 {C1C0D748~ 272000 2014~ N19 3DY  F     N       L        23    NA    PARTI~ NA       LOND~ ISLINGT~ GREAT~ A     A
 9 {C1C0D748~ 272000 2014~ N19 3DY  F     N       L        23    NA    PARTI~ NA       LOND~ ISLINGT~ GREAT~ A     A
10 {C1C0D748~ 272000 2014~ N19 3DY  F     N       L        23    NA    PARTI~ NA       LOND~ ISLINGT~ GREAT~ A     A
# ... with 19,073,610 more rows, and 1 more variable: mean_price <dbl>
    enter code here

A tibble: 339,500 x 4
# Groups:   DISTRICT [34]
    PRICE DISTRICT       mean_price MEAN_PRICE
    <int> <chr>               <dbl>      <dbl>
 1 562500 SOUTHWARK         779138.    779138.
 2 272000 ISLINGTON         897315.    897315.
 3 350000 LEWISHAM          451338.    451338.
 4 331000 NEWHAM            416543.    416543.
 5 534250 LAMBETH           638344.    638344.
 6 530000 LEWISHAM          451338.    451338.
 7 855000 WANDSWORTH        778023.    778023.
 8 242500 ENFIELD           448493.    448493.
 9 685000 ISLINGTON         897315.    897315.
10 250000 WALTHAM FOREST    428074.    428074.
# ... with 339,490 more rows
</code>```

答:
You should assign the result to tekoopl:</p>
```<code>tekoopl <- tekoopl %>% group_by(DISTRICT)%>% mutate(new_column= PRICE - MEAN_PRICE_DISTRICT)
</code>```

Title: subtract 2 colums from each other

Body:
I need to make a new column PRICE minus MEAN_PRICE_DISTRICT. I have tried this, but it does not work? how to subtract 2 columns from each other, my idea was probably too simple :-)

tekoopl %>%  group_by(DISTRICT)%>%  mutate(new_column= PRICE - MEAN_PRICE_DISTRICT)

I have only just started with R ;-)
(I am currently using the packages dplyr and tidyr)

A tibble: 19,073,620 x 17
# Groups:   PRICE [24,547]
   ID          PRICE DATE  POSTCODE TYPE  OLD_NEW DURATION PAON  SAON  STREET LOCALITY TOWN  DISTRICT COUNTY PPD   STATUS
   <chr>       <int> <chr> <chr>    <chr> <chr>   <chr>    <chr> <chr> <chr>  <chr>    <chr> <chr>    <chr>  <chr> <chr>
 1 {CCA5ACA8~ 562500 2014~ SE1 0FT  F     Y       L        ROSL~ APAR~ EWER ~ NA       LOND~ SOUTHWA~ GREAT~ A     A
 2 {CCA5ACA8~ 562500 2014~ SE1 0FT  F     Y       L        ROSL~ APAR~ EWER ~ NA       LOND~ SOUTHWA~ GREAT~ A     A
 3 {CCA5ACA8~ 562500 2014~ SE1 0FT  F     Y       L        ROSL~ APAR~ EWER ~ NA       LOND~ SOUTHWA~ GREAT~ A     A
 4 {CCA5ACA8~ 562500 2014~ SE1 0FT  F     Y       L        ROSL~ APAR~ EWER ~ NA       LOND~ SOUTHWA~ GREAT~ A     A
 5 {CCA5ACA8~ 562500 2014~ SE1 0FT  F     Y       L        ROSL~ APAR~ EWER ~ NA       LOND~ SOUTHWA~ GREAT~ A     A
 6 {CCA5ACA8~ 562500 2014~ SE1 0FT  F     Y       L        ROSL~ APAR~ EWER ~ NA       LOND~ SOUTHWA~ GREAT~ A     A
 7 {CCA5ACA8~ 562500 2014~ SE1 0FT  F     Y       L        ROSL~ APAR~ EWER ~ NA       LOND~ SOUTHWA~ GREAT~ A     A
 8 {C1C0D748~ 272000 2014~ N19 3DY  F     N       L        23    NA    PARTI~ NA       LOND~ ISLINGT~ GREAT~ A     A
 9 {C1C0D748~ 272000 2014~ N19 3DY  F     N       L        23    NA    PARTI~ NA       LOND~ ISLINGT~ GREAT~ A     A
10 {C1C0D748~ 272000 2014~ N19 3DY  F     N       L        23    NA    PARTI~ NA       LOND~ ISLINGT~ GREAT~ A     A
# ... with 19,073,610 more rows, and 1 more variable: mean_price <dbl>
    enter code here

A tibble: 339,500 x 4
# Groups:   DISTRICT [34]
    PRICE DISTRICT       mean_price MEAN_PRICE
    <int> <chr>               <dbl>      <dbl>
 1 562500 SOUTHWARK         779138.    779138.
 2 272000 ISLINGTON         897315.    897315.
 3 350000 LEWISHAM          451338.    451338.
 4 331000 NEWHAM            416543.    416543.
 5 534250 LAMBETH           638344.    638344.
 6 530000 LEWISHAM          451338.    451338.
 7 855000 WANDSWORTH        778023.    778023.
 8 242500 ENFIELD           448493.    448493.
 9 685000 ISLINGTON         897315.    897315.
10 250000 WALTHAM FOREST    428074.    428074.
# ... with 339,490 more rows

Body:
You should assign the result to tekoopl:

tekoopl <- tekoopl %>% group_by(DISTRICT)%>% mutate(new_column= PRICE - MEAN_PRICE_DISTRICT)


答:
First of all, you can't (or - you shouldn't) test void methods. You are testing the output of the method - which Main does not have. Second thought: you cannot mock (simulate) an Console object. Read some tutorials about mock and mocking.

Sample method with sample test could look similar to this:

```<code>public class SimpleCalculator
{
    public int SumTwoNumbers(int number1, int number2)
    {
        return number1 + number2;
    }
}

[TestClass]
public class TestClass
{
    [TestMethod]
    public void Test_SimpleCalculator_SumTwoNumbers_CorrectValues()
    {
        // Arrange
        SimpleCalculator calc = new SimpleCalculator();

        // Act
        int result = calc.SumTwoNumbers(5, 2);

        // Assert
        Assert.AreEqual(7, result);
    }
}
</code>```

Hope this helped a little.

Title: Help me my first test

Body:
First of all, you can't (or - you shouldn't) test void methods. You are testing the output of the method - which Main does not have. Second thought: you cannot mock (simulate) an Console object. Read some tutorials about mock and mocking.

Sample method with sample test could look similar to this:

public class SimpleCalculator
{
    public int SumTwoNumbers(int number1, int number2)
    {
        return number1 + number2;
    }
}

[TestClass]
public class TestClass
{
    [TestMethod]
    public void Test_SimpleCalculator_SumTwoNumbers_CorrectValues()
    {
        // Arrange
        SimpleCalculator calc = new SimpleCalculator();

        // Act
        int result = calc.SumTwoNumbers(5, 2);

        // Assert
        Assert.AreEqual(7, result);
    }
}

Hope this helped a little.


问:
Model returns only NaN values on GTXA5000 but not on 1080TI
I have replaced a GTX 1080TI graphics card with a GTX A5000 in a desktop machine and reinstalled Ubuntu to upgraded from 16.04 to 20.04 in order to meet requirements.
But now I can't retrain or predict with our current model; When loading the model, Keras hangs for a very long time and all predicted results are NaN values.
We use Keras 2.2.4 with tensorflow 2.1.0 and Cuda 10.1.243, which I installed using Conda and I have tried with different drivers.

If I put the old GTX 1080 TI card back in to the machine the code works fine.

Any idea of what can be wrong - can it be the case that the A5000 does not support the same models as an old 1080TI card?

答:
Ok, I can confirm that this setup works on the GTX A5000

CUDA: 11.6.0

Tensorflow: 2.7.0

Driver Version: 510.47.03

Thanks to @talonmies for his comment.


问:
configuration.isOn.toggle() Not working in Custom Toggle in SwiftUI
I have made a screen where I used a custom toggle. But when I am tapping on the toggle button, it's always printing "isOff" because the configuration.toggle value is not updating and is always set to false.</p>
```<code>struct TestToggleView: View {
    @Binding private var isOn: Bool

     init(isOn: Binding<Bool>) {
         _isOn = isOn
     }

     public var body: some View {
         Toggle(isOn: $isOn, label: {
             Text("Hi)
         })
         .toggleStyle(ToggleStyle())
     }
}

</code>```
```<code>private struct ButtonToggleStyle: ToggleStyle {

    func makeBody(configuration: Configuration) -> some View {
        HStack(alignment: .center) {
                             configuration.label
                             Text("Yes")
        }.frame(maxWidth: .infinity)
                          .onTapGesture {
                              configuration.isOn.toggle()
                              if configuration.isOn {
                                  print("isOn")
                              } else {
                                  print("isOff")
                          }
                          }
                          .onAppear {
                              print(configuration.isOn)
                   }
           }
    }
}
</code>```

答:
Well, you should not name your custom ToggleStyle ToggleStyle.

To change the isOn value you have to go to the wrappedValue:
configuration.$isOn.wrappedValue.toggle()

Here is a complete example:

```<code>struct ContentView: View {

    @State private var isOn = false

    var body: some View {
        Toggle(isOn: $isOn, label: {
            Text("Hi") })
            .toggleStyle(MyToggleStyle())
    }
}

struct MyToggleStyle: ToggleStyle {

    func makeBody(configuration: Configuration) -> some View {
        HStack(alignment: .center) {
            configuration.label
            Text(configuration.isOn ? "Yes" : "No")
        }.frame(maxWidth: .infinity)

            .onTapGesture {
                configuration.$isOn.wrappedValue.toggle()
            }
    }
}
</code>```

Body:
I have made a screen where I used a custom toggle. But when I am tapping on the toggle button, it's always printing "isOff" because the configuration.toggle value is not updating and is always set to false.

struct TestToggleView: View {
    @Binding private var isOn: Bool

     init(isOn: Binding<Bool>) {
         _isOn = isOn
     }

     public var body: some View {
         Toggle(isOn: $isOn, label: {
             Text("Hi)
         })
         .toggleStyle(ToggleStyle())
     }
}

private struct ButtonToggleStyle: ToggleStyle {

    func makeBody(configuration: Configuration) -> some View {
        HStack(alignment: .center) {
                             configuration.label
                             Text("Yes")
        }.frame(maxWidth: .infinity)
                          .onTapGesture {
                              configuration.isOn.toggle()
                              if configuration.isOn {
                                  print("isOn")
                              } else {
                                  print("isOff")
                          }
                          }
                          .onAppear {
                              print(configuration.isOn)
                   }
           }
    }
}

Body:
Well, you should not name your custom ToggleStyle ToggleStyle.

To change the isOn value you have to go to the wrappedValue:
configuration.$isOn.wrappedValue.toggle()

Here is a complete example:

struct ContentView: View {

    @State private var isOn = false

    var body: some View {
        Toggle(isOn: $isOn, label: {
            Text("Hi") })
            .toggleStyle(MyToggleStyle())
    }
}

struct MyToggleStyle: ToggleStyle {

    func makeBody(configuration: Configuration) -> some View {
        HStack(alignment: .center) {
            configuration.label
            Text(configuration.isOn ? "Yes" : "No")
        }.frame(maxWidth: .infinity)

            .onTapGesture {
                configuration.$isOn.wrappedValue.toggle()
            }
    }
}


问:
How to get arg values from a subfunction's decorator?
```<code>def decorator(*args, **kwargs):
    def inner(f):
        print(kwargs['here'])
        return f
    return inner

class Test:
    def test(self, a, b):
        @decorator(here='access/change this value')
        def add(a, b):
            print(a + b)
        add(a, b)
        return

if __name__ == '__main__':
    t = Test()
    t.test(1, 2)
</code>```

How to use "t" to extract or change the value "access/change this value" from a decorator's args on a subfunction. getattribute can only help get function(self) not subfunction, am I right?

For example, I would like to get the value "access/change this value" without running function test.  Or change arg here = [original str] + "a new str"

答:
If you change class Test slightly, you can do this in a reasonable simple way

def decorator(*args, **kwargs):
    def inner(f):
        print(kwargs['here'])
        return f
    return inner

class Test:
    here = "access/change this value" # 1. Add this class member
    def test(self, a, b):
        @decorator(here=self.here) # 2. Use the class member as a decorator kwarg
        def add(a, b):
            print(a + b)
        add(a, b)

if __name__ == '__main__':
    t = Test()
    t.here = "a new value"
    t.test(1, 2)
```

I believe this lets you do what you want to do with the decorator, and it doesn't require deep diving into the innards of python objects like in this answer (which might be of interest if you actually did want to play surgeon on python function objects).

Body:
def decorator(*args, **kwargs):
    def inner(f):
        print(kwargs['here'])
        return f
    return inner

class Test:
    def test(self, a, b):
        @decorator(here='access/change this value')
        def add(a, b):
            print(a + b)
        add(a, b)
        return

if __name__ == '__main__':
    t = Test()
    t.test(1, 2)

How to use "t" to extract or change the value "access/change this value" from a decorator's args on a subfunction. getattribute can only help get function(self) not subfunction, am I right?

For example, I would like to get the value "access/change this value" without running function test.  Or change arg here = [original str] + "a new str"

Body:
If you change class Test slightly, you can do this in a reasonable simple way

def decorator(*args, **kwargs):
    def inner(f):
        print(kwargs['here'])
        return f
    return inner

class Test:
    here = "access/change this value" # 1. Add this class member
    def test(self, a, b):
        @decorator(here=self.here) # 2. Use the class member as a decorator kwarg
        def add(a, b):
            print(a + b)
        add(a, b)

if __name__ == '__main__':
    t = Test()
    t.here = "a new value"
    t.test(1, 2)

I believe this lets you do what you want to do with the decorator, and it doesn't require deep diving into the innards of python objects like in this answer (which might be of interest if you actually did want to play surgeon on python function objects).


问:
HAL_UARTEx_RxEventCallback() circular DMA: What address is the data?
I'm using the HAL with an STM32F3xx, implementing UART receive with circular DMA. The data should continually be received into the huart->pRxBuffPtr buffer, overwriting old data as new data arrives, and the HAL_UARTEx_RxEventCallback() function gets called regularly to copy out the data before it gets overwritten. The HAL_UARTEx_RxEventCallback() function receives a size parameter and of course a pointer huart, but no direct indication of where in the huart->pRxBuffPtr the freshly arrived data was DMA'd to.

How do I know whereabouts in huart->pRxBuffPtr the freshly arrived data starts?

答:
Thank you to Tom V for the hint. For future generations, here is the solution code - a function which returns true and gets the next available byte, otherwise returns false:</p>
```<code>bool uart_receiveByte(uint8_t *pData) {
  static size_t dmaTail = 0u;

  bool isByteReceived = false;

  // dmaHead is the next position in the buffer the DMA will write to.
  // dmaTail is the next position in the buffer to be read from.
  const size_t dmaHead = huart->RxXferSize - huart->hdmarx->Instance->CNDTR;

  if (dmaTail != dmaHead) {
    isByteReceived = true;
    *pData = pRxDmaBuffer[dmaTail];
    if (++dmaTail >= huart->RxXferSize) {
      dmaTail = 0u;
    }
  }

  return isByteReceived;
}
</code>```

Body:
Thank you to Tom V for the hint. For future generations, here is the solution code - a function which returns true and gets the next available byte, otherwise returns false:

bool uart_receiveByte(uint8_t *pData) {
  static size_t dmaTail = 0u;

  bool isByteReceived = false;

  // dmaHead is the next position in the buffer the DMA will write to.
  // dmaTail is the next position in the buffer to be read from.
  const size_t dmaHead = huart->RxXferSize - huart->hdmarx->Instance->CNDTR;

  if (dmaTail != dmaHead) {
    isByteReceived = true;
    *pData = pRxDmaBuffer[dmaTail];
    if (++dmaTail >= huart->RxXferSize) {
      dmaTail = 0u;
    }
  }

  return isByteReceived;
}


问:
Starting a new thread and returning the main thread Spring webflux methods subscribeOn
I have a Spring Webflux application in which I want to spawn a new Thread for a time consuming operation and as soon as the new thread is spawned return the main thread so that client is not kept waiting

Please note the time consuming method is not a WebClient call but a service layer function call to download files from a content storage. I have defined a CallableTask class as below

```<code>public class DocumentProcessorCallableTask<T> {

    public Mono<T> execute(Callable<T> task) {
        return Mono.defer(
            () -> Mono.fromCallable(task)
                      .doOnError(throwable ->
                          Mono.error(new
        ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR))));
    }
}
</code>```

And the method in which I want to spawn a new thread is as below. The method named downloadAndUploadSaveLandsDocuments is the one which makes a call to the content storage to get documents

```<code>private Mono<MarsTxnResponse> subscribeOnScheduler(MarsTxnResponse rsp, Long clientId) {
    return new DocumentProcessorCallableTask<Mono<MarsTxnResponse>>()
        .execute(() -> downloadAndUploadSaveLandsDocuments(rsp, clientId))
        .subscribeOn(Schedulers.boundedElastic())
        .thenReturn(rsp);
</code>```

The problem is that a new thread is created but the webflux code inside downloadAndUploadSaveLandsDocuments is not executed.

It gets executed when I change the above code to below BUT the main thread waits until the newly spawned thread completes which I dont want.
Does subscribeOn and publishOn work only from the context of a Webclient call?

```<code>return new DocumentProcessorCallableTask<Mono<MarsTxnResponse>>()
        .execute(() -> downloadAndUploadSaveLandsDocuments(rsp, clientId))
        .flatMap(marsTxnResponseMono -> marsTxnResponseMono)
        .subscribeOn(Schedulers.boundedElastic());
</code>```

The method which calls the content storage is as below.It does not enter Flux.fromIterable in the first case but does enter it in the second case.

```<code>public Mono<MarsTxnResponse> downloadAndUploadSaveLandsDocuments(
      MarsTxnResponse rsp,
      Long clientId) {
    return Flux.fromIterable(rsp.getExpandedWebLtLandList())
                .flatMap(webLtLandFromRequest -> {
                      return downloadDocuments(rsp, webLtLandFromRequest, clientId);
                }).collectList()
                .flatMap(objects -> {
                    return documentAsyncUploadService.uploadFilesIfExists(rsp);
                });
}
</code>```

I am using spring-boot 2.4.13 and spring-boot-starter-webflux version 2.4.13

答:
Finally the code which worked

```<code>    return Mono.just(rsp)
        .flatMap(
            marsTxnResponse -> {
              new DocumentProcessorCallableTask<Mono<MarsTxnResponse>>()
                  .execute(() -> downloadAndUploadSaveLandsDocuments(rsp, clientId))
                  .flatMap(marsTxnResponseMono -> marsTxnResponseMono)
                  .subscribeOn(Schedulers.boundedElastic())
                  .subscribe();
              return Mono.just(rsp);
            });
</code>```

The most important thing to add was subscribe() after subscribeOn(Schedulers.boundedElastic())

Body:
I have a Spring Webflux application in which I want to spawn a new Thread for a time consuming operation and as soon as the new thread is spawned return the main thread so that client is not kept waiting

Please note the time consuming method is not a WebClient call but a service layer function call to download files from a content storage. I have defined a CallableTask class as below

public class DocumentProcessorCallableTask<T> {

    public Mono<T> execute(Callable<T> task) {
        return Mono.defer(
            () -> Mono.fromCallable(task)
                      .doOnError(throwable ->
                          Mono.error(new
        ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR))));
    }
}

And the method in which I want to spawn a new thread is as below. The method named downloadAndUploadSaveLandsDocuments is the one which makes a call to the content storage to get documents

private Mono<MarsTxnResponse> subscribeOnScheduler(MarsTxnResponse rsp, Long clientId) {
    return new DocumentProcessorCallableTask<Mono<MarsTxnResponse>>()
        .execute(() -> downloadAndUploadSaveLandsDocuments(rsp, clientId))
        .subscribeOn(Schedulers.boundedElastic())
        .thenReturn(rsp);

The problem is that a new thread is created but the webflux code inside downloadAndUploadSaveLandsDocuments is not executed.

It gets executed when I change the above code to below BUT the main thread waits until the newly spawned thread completes which I dont want.
Does subscribeOn and publishOn work only from the context of a Webclient call?

return new DocumentProcessorCallableTask<Mono<MarsTxnResponse>>()
        .execute(() -> downloadAndUploadSaveLandsDocuments(rsp, clientId))
        .flatMap(marsTxnResponseMono -> marsTxnResponseMono)
        .subscribeOn(Schedulers.boundedElastic());

The method which calls the content storage is as below.It does not enter Flux.fromIterable in the first case but does enter it in the second case.

public Mono<MarsTxnResponse> downloadAndUploadSaveLandsDocuments(
      MarsTxnResponse rsp,
      Long clientId) {
    return Flux.fromIterable(rsp.getExpandedWebLtLandList())
                .flatMap(webLtLandFromRequest -> {
                      return downloadDocuments(rsp, webLtLandFromRequest, clientId);
                }).collectList()
                .flatMap(objects -> {
                    return documentAsyncUploadService.uploadFilesIfExists(rsp);
                });
}

I am using spring-boot 2.4.13 and spring-boot-starter-webflux version 2.4.13

Body:
Finally the code which worked

    return Mono.just(rsp)
        .flatMap(
            marsTxnResponse -> {
              new DocumentProcessorCallableTask<Mono<MarsTxnResponse>>()
                  .execute(() -> downloadAndUploadSaveLandsDocuments(rsp, clientId))
                  .flatMap(marsTxnResponseMono -> marsTxnResponseMono)
                  .subscribeOn(Schedulers.boundedElastic())
                  .subscribe();
              return Mono.just(rsp);
            });

The most important thing to add was subscribe() after subscribeOn(Schedulers.boundedElastic())


问:
Apply function to a list of lists
I have a list of length 100. Each entry is itself a list containing 31 matrices with 10 rows and five columns.

```<code>>length(dati_fault)
[1] 100
</code>```
```<code>> length(dati_fault[[1]])
[1] 31
</code>```

I should get 100 averages of the variables summarizing the 31 matrices each element of the list

```<code>media_1<-list()
for(i in nrow(dati_fault)){
  for(j in nrow(dati_fault[[i]]))
  media_1[[i]]<-lapply(dati_fault, colMeans(j))

}
media_1
</code>```

But I get nothing because the media_1 list remains empty

答:
you don't need for  loops to do so. You can directly work with lapply:

```<code>lapply(dati_fault, \(x) colMeans(do.call(rbind, x)))
</code>```

This does the following: for each entry of dati_fault (i.e. each sublist of 31 matrices) these matrices are bound together (using rbind) into one single matrix with 310 rows and 5 columns. Then, colMeans is applied to this matrix.

If you are not familiar with the shorthand notation for anonymous functions (i.e. \(x)) you can read about it here.

Title: Apply function to a list of lists

Body:
I have a list of length 100. Each entry is itself a list containing 31 matrices with 10 rows and five columns.

>length(dati_fault)
[1] 100

> length(dati_fault[[1]])
[1] 31

I should get 100 averages of the variables summarizing the 31 matrices each element of the list

media_1<-list()
for(i in nrow(dati_fault)){
  for(j in nrow(dati_fault[[i]]))
  media_1[[i]]<-lapply(dati_fault, colMeans(j))

}
media_1

But I get nothing because the media_1 list remains empty

Body:
you don't need for  loops to do so. You can directly work with lapply:

lapply(dati_fault, \(x) colMeans(do.call(rbind, x)))

This does the following: for each entry of dati_fault (i.e. each sublist of 31 matrices) these matrices are bound together (using rbind) into one single matrix with 310 rows and 5 columns. Then, colMeans is applied to this matrix.

If you are not familiar with the shorthand notation for anonymous functions (i.e. \(x)) you can read about it here.


问:
convert complex nested json array using jolt expression in nifi
I have a complex Json where i wanted to flatten the Json using Jolt or any other ways to flatten in Nifi is also fine
can anyone please help to flatten the below JSON

{
  "veread": "ndjdjjywuieopppqpppwaghhzuii",
  "debittanceInformation": [
    {
      "internalDocumentInformation": [
        {
          "number": "8",
          "lineDetails": [
            {
              "identifications": [
                {
                  "number": "44",
                  "model": {
                    "code": "xdd",
                    "proprietary": "ddy"
                  },
                  "relatedDate": "3/4"
                }
              ],
              "quantity": 136,
              "unitOfMeasure": "each",
              "money": {
                "duePayablemoney": 44,
                "discountAppliedmoneys": [
                  {
                    "model": {
                      "code": "dddddd",
                      "proprietary": "rddddy"
                    },
                    "money": 216.2
                  }
                ],
                "valuemoneys": [
                  {
                    "model": {
                      "code": "ddddd",
                      "proprietary": "dddd"
                    },
                    "money": 391.41
                  }
                ],
                "adjustmentmoneyAndReasons": [
                  {
                    "money": 824.54,
                    "reason": "dd"
                  }
                ],
                "debittedmoney": 660.7,
                "creditNotemoney": 985.63
              }
            }
          ],
          "internalDocumentmoney": {
            "duePayablemoney": 567.45,
            "discountAppliedmoneys": [
              {
                "model": {
                  "code": "DD",
                  "proprietary": "EE"
                },
                "money": 5.64
              }
            ],
            "valuemoneys": [
              {
                "model": {
                  "code": "z",
                  "proprietary": "a"
                },
                "money": 145
              }
            ],
            "adjustmentmoneyAndReasons": [
              {
                "money": 678,
                "reason": "tyuiop"
              }
            ],
            "debittedmoney": 123,
            "creditNotemoney": 456
          }
        }
      ],
      "supplierReferenceInformation": {
        "model": {
          "code": "x",
          "proprietary": "y"
        },
        "issuer": "issuer",
        "reference": "hfhjfdozkdfl;fdko;k"
      },
      "billr": {
        "name": "jdjaiofjiosJOfjaiodjoiwaj",
        "companyIdentifications": [
          {
            "identification": "74747435438",
            "model": "jdidfjdsjf"
          }
        ]
      },
      "bille": {
        "name": "djhsaijdwjadfja;dddF",
        "companyIdentifications": [
          {
            "identification": "dddddd",
            "model": "kksjdadawx"
          }
        ]
      },
      "additionaldebittanceInformation": [
        "dd",
        "xnjasndfjafnlkNDflkhlfkacmakjhfncasklnf"
      ]
    }
  ],
  "chargesInformation": []
}
```
<p>The above is My Json which I need to flatten in to simple JSON so that I can process it in Hive .
i have tried using Flatten JSON processor but it is not working so now I an trying using jolt spec
can any one please guide me with above issue using either Jolt transformation or in Nifi.</p>
<p>my expected output should be as below</p>
<pre class="lang-json prettyprint-override"><code>{
    "veread": "ndjdjjywuieopppqpppwaghhzuii",
    "ddddwww_internalDocumentInformation_number": "8",
    "ddddwww_internalDocumentInformation_lineDetails_identifications_number": "1025",
    "ddddwww_internalDocumentInformation_lineDetails_identifications_model.code": "x",
    "ddddwww_internalDocumentInformation_lineDetails_identifications_model.proprietary": "y",
    "ddddwww_internalDocumentInformation_lineDetails_identifications_relatedDate": "3/23",
    "ddddwww_internalDocumentInformation_lineDetails_quantity": 136,
    "ddddwww_internalDocumentInformation_lineDetails_unitOfMeasure": "each",
    "ddddwww_internalDocumentInformation_lineDetails_money.duePayablemoney": 957.86,
    "ddddwww_internalDocumentInformation_lineDetails_money.discountAppliedmoneys_model.code": "dvbnqwe",
    "ddddwww_internalDocumentInformation_lineDetails_money.discountAppliedmoneys_model.proprietary": "rqazloy",
    "ddddwww_internalDocumentInformation_lineDetails_money.discountAppliedmoneys_money": 216.2,
    "ddddwww_internalDocumentInformation_lineDetails_money.valuemoneys_model.code": "YUIO",
    "ddddwww_internalDocumentInformation_lineDetails_money.valuemoneys_model.proprietary": "BHRTY",
    "ddddwww_internalDocumentInformation_lineDetails_money.valuemoneys_money": 391.41,
    "ddddwww_internalDocumentInformation_lineDetails_money.adjustmentmoneyAndReasons_money": 824.54,
    "ddddwww_internalDocumentInformation_lineDetails_money.adjustmentmoneyAndReasons_reason": "BONUS",
    "ddddwww_internalDocumentInformation_lineDetails_money.debittedmoney": 660.7,
    "ddddwww_internalDocumentInformation_lineDetails_money.creditNotemoney": 985.63,
    "ddddwww_internalDocumentInformation_internalDocumentmoney.duePayablemoney": 567.45,
    "ddddwww_internalDocumentInformation_internalDocumentmoney.discountAppliedmoneys_model.code": "DD",
    "ddddwww_internalDocumentInformation_internalDocumentmoney.discountAppliedmoneys_model.proprietary": "EE",
    "ddddwww_internalDocumentInformation_internalDocumentmoney.discountAppliedmoneys_money": 5.64,
    "ddddwww_internalDocumentInformation_internalDocumentmoney.valuemoneys_model.code": "z",
    "ddddwww_internalDocumentInformation_internalDocumentmoney.valuemoneys_model.proprietary": "a",
    "ddddwww_internalDocumentInformation_internalDocumentmoney.valuemoneys_money": 145,
    "ddddwww_internalDocumentInformation_internalDocumentmoney.adjustmentmoneyAndReasons_money": 678,
    "ddddwww_internalDocumentInformation_internalDocumentmoney.adjustmentmoneyAndReasons_reason": "tyuiop",
    "ddddwww_internalDocumentInformation_internalDocumentmoney.debittedmoney": 123,
    "ddddwww_internalDocumentInformation_internalDocumentmoney.creditNotemoney": 456,
    "ddddwww_supplierReferenceInformation.model.code": "x",
    "ddddwww_supplierReferenceInformation.model.proprietary": "y",
    "ddddwww_supplierReferenceInformation.issuer": "issuer",
    "ddddwww_supplierReferenceInformation.reference": "hfhjfdozkdfl;fdko;k",
    "ddddwww_billr.name": "jdjaiofjiosJOfjaiodjoiwaj",
    "ddddwww_billr.companyIdentifications_identification": "74747435438",
    "ddddwww_billr.companyIdentifications_model": "jdidfjdsjf",
    "ddddwww_bille.name": "djhsaijdwjadfja;lMEjknEAKDLJOJRF",
    "ddddwww_bille.companyIdentifications_identification": "mkskfsajdwiojdijRUWa",
    "ddddwww_bille.companyIdentifications_model": "kksjdadawx",
    "ddddwww_additionalddddwww[0]": "JDSJAHDJKLJHRFQWJESJqiorwjd",
    "ddddwww_additionalddddwww[1]": "xnjasndfjafnlkNDflkhlfkacmakjhfncasklnf",
    "chargesInformation": []
}
</code>```

I have updated the request

答:
Use FlattenJson processor with properties:

Separator: _

Flatten Mode: normal

Output json:

{
  "transactionId" : "ndjdjjywuieopppqpppwaghhzuii",
  "debittanceInformation[0]_internalDocumentInformation[0]_number" : "8",
  "debittanceInformation[0]_internalDocumentInformation[0]_lineDetails[0]_identifications[0]_number" : "1025",
  "debittanceInformation[0]_internalDocumentInformation[0]_lineDetails[0]_identifications[0]_model_code" : "x",
  "debittanceInformation[0]_internalDocumentInformation[0]_lineDetails[0]_identifications[0]_model_proprietary" : "y",
  "debittanceInformation[0]_internalDocumentInformation[0]_lineDetails[0]_identifications[0]_relatedDate" : "3\/23",
  "debittanceInformation[0]_internalDocumentInformation[0]_lineDetails[0]_quantity" : 136,
  "debittanceInformation[0]_internalDocumentInformation[0]_lineDetails[0]_unitOfMeasure" : "each",
  "debittanceInformation[0]_internalDocumentInformation[0]_lineDetails[0]_money_duePayablemoney" : 957.86,
  "debittanceInformation[0]_internalDocumentInformation[0]_lineDetails[0]_money_discountAppliedmoneys[0]_model_code" : "dvbnqwe",
  "debittanceInformation[0]_internalDocumentInformation[0]_lineDetails[0]_money_discountAppliedmoneys[0]_model_proprietary" : "rqazloy",
  "debittanceInformation[0]_internalDocumentInformation[0]_lineDetails[0]_money_discountAppliedmoneys[0]_money" : 216.2,
  "debittanceInformation[0]_internalDocumentInformation[0]_lineDetails[0]_money_valuemoneys[0]_model_code" : "YUIO",
  "debittanceInformation[0]_internalDocumentInformation[0]_lineDetails[0]_money_valuemoneys[0]_model_proprietary" : "BHRTY",
  "debittanceInformation[0]_internalDocumentInformation[0]_lineDetails[0]_money_valuemoneys[0]_money" : 391.41,
  "debittanceInformation[0]_internalDocumentInformation[0]_lineDetails[0]_money_adjustmentmoneyAndReasons[0]_money" : 824.54,
  "debittanceInformation[0]_internalDocumentInformation[0]_lineDetails[0]_money_adjustmentmoneyAndReasons[0]_reason" : "BONUS",
  "debittanceInformation[0]_internalDocumentInformation[0]_lineDetails[0]_money_debittedmoney" : 660.7,
  "debittanceInformation[0]_internalDocumentInformation[0]_lineDetails[0]_money_creditNotemoney" : 985.63,
  "debittanceInformation[0]_internalDocumentInformation[0]_internalDocumentmoney_duePayablemoney" : 567.45,
  "debittanceInformation[0]_internalDocumentInformation[0]_internalDocumentmoney_discountAppliedmoneys[0]_model_code" : "DD",
  "debittanceInformation[0]_internalDocumentInformation[0]_internalDocumentmoney_discountAppliedmoneys[0]_model_proprietary" : "EE",
  "debittanceInformation[0]_internalDocumentInformation[0]_internalDocumentmoney_discountAppliedmoneys[0]_money" : 5.64,
  "debittanceInformation[0]_internalDocumentInformation[0]_internalDocumentmoney_valuemoneys[0]_model_code" : "z",
  "debittanceInformation[0]_internalDocumentInformation[0]_internalDocumentmoney_valuemoneys[0]_model_proprietary" : "a",
  "debittanceInformation[0]_internalDocumentInformation[0]_internalDocumentmoney_valuemoneys[0]_money" : 145,
  "debittanceInformation[0]_internalDocumentInformation[0]_internalDocumentmoney_adjustmentmoneyAndReasons[0]_money" : 678,
  "debittanceInformation[0]_internalDocumentInformation[0]_internalDocumentmoney_adjustmentmoneyAndReasons[0]_reason" : "tyuiop",
  "debittanceInformation[0]_internalDocumentInformation[0]_internalDocumentmoney_debittedmoney" : 123,
  "debittanceInformation[0]_internalDocumentInformation[0]_internalDocumentmoney_creditNotemoney" : 456,
  "debittanceInformation[0]_supplierReferenceInformation_model_code" : "x",
  "debittanceInformation[0]_supplierReferenceInformation_model_proprietary" : "y",
  "debittanceInformation[0]_supplierReferenceInformation_issuer" : "issuer",
  "debittanceInformation[0]_supplierReferenceInformation_reference" : "hfhjfdozkdfl;fdko;k",
  "debittanceInformation[0]_billr_name" : "jdjaiofjiosJOfjaiodjoiwaj",
  "debittanceInformation[0]_billr_companyIdentifications[0]_identification" : "74747435438",
  "debittanceInformation[0]_billr_companyIdentifications[0]_model" : "jdidfjdsjf",
  "debittanceInformation[0]_bille_name" : "djhsaijdwjadfja;lMEjknEAKDLJOJRF",
  "debittanceInformation[0]_bille_companyIdentifications[0]_identification" : "mkskfsajdwiojdijRUWa",
  "debittanceInformation[0]_bille_companyIdentifications[0]_model" : "kksjdadawx",
  "debittanceInformation[0]_additionaldebittanceInformation[0]" : "JDSJAHDJKLJHRFQWJESJqiorwjd",
  "debittanceInformation[0]_additionaldebittanceInformation[1]" : "xnjasndfjafnlkNDflkhlfkacmakjhfncasklnf",
  "chargesInformation" : [  ]
}
```

Body:
I have a complex Json where i wanted to flatten the Json using Jolt or any other ways to flatten in Nifi is also fine
can anyone please help to flatten the below JSON

{
  "veread": "ndjdjjywuieopppqpppwaghhzuii",
  "debittanceInformation": [
    {
      "internalDocumentInformation": [
        {
          "number": "8",
          "lineDetails": [
            {
              "identifications": [
                {
                  "number": "44",
                  "model": {
                    "code": "xdd",
                    "proprietary": "ddy"
                  },
                  "relatedDate": "3/4"
                }
              ],
              "quantity": 136,
              "unitOfMeasure": "each",
              "money": {
                "duePayablemoney": 44,
                "discountAppliedmoneys": [
                  {
                    "model": {
                      "code": "dddddd",
                      "proprietary": "rddddy"
                    },
                    "money": 216.2
                  }
                ],
                "valuemoneys": [
                  {
                    "model": {
                      "code": "ddddd",
                      "proprietary": "dddd"
                    },
                    "money": 391.41
                  }
                ],
                "adjustmentmoneyAndReasons": [
                  {
                    "money": 824.54,
                    "reason": "dd"
                  }
                ],
                "debittedmoney": 660.7,
                "creditNotemoney": 985.63
              }
            }
          ],
          "internalDocumentmoney": {
            "duePayablemoney": 567.45,
            "discountAppliedmoneys": [
              {
                "model": {
                  "code": "DD",
                  "proprietary": "EE"
                },
                "money": 5.64
              }
            ],
            "valuemoneys": [
              {
                "model": {
                  "code": "z",
                  "proprietary": "a"
                },
                "money": 145
              }
            ],
            "adjustmentmoneyAndReasons": [
              {
                "money": 678,
                "reason": "tyuiop"
              }
            ],
            "debittedmoney": 123,
            "creditNotemoney": 456
          }
        }
      ],
      "supplierReferenceInformation": {
        "model": {
          "code": "x",
          "proprietary": "y"
        },
        "issuer": "issuer",
        "reference": "hfhjfdozkdfl;fdko;k"
      },
      "billr": {
        "name": "jdjaiofjiosJOfjaiodjoiwaj",
        "companyIdentifications": [
          {
            "identification": "74747435438",
            "model": "jdidfjdsjf"
          }
        ]
      },
      "bille": {
        "name": "djhsaijdwjadfja;dddF",
        "companyIdentifications": [
          {
            "identification": "dddddd",
            "model": "kksjdadawx"
          }
        ]
      },
      "additionaldebittanceInformation": [
        "dd",
        "xnjasndfjafnlkNDflkhlfkacmakjhfncasklnf"
      ]
    }
  ],
  "chargesInformation": []
}

The above is My Json which I need to flatten in to simple JSON so that I can process it in Hive .
i have tried using Flatten JSON processor but it is not working so now I an trying using jolt spec
can any one please guide me with above issue using either Jolt transformation or in Nifi.

my expected output should be as below

{
    "veread": "ndjdjjywuieopppqpppwaghhzuii",
    "ddddwww_internalDocumentInformation_number": "8",
    "ddddwww_internalDocumentInformation_lineDetails_identifications_number": "1025",
    "ddddwww_internalDocumentInformation_lineDetails_identifications_model.code": "x",
    "ddddwww_internalDocumentInformation_lineDetails_identifications_model.proprietary": "y",
    "ddddwww_internalDocumentInformation_lineDetails_identifications_relatedDate": "3/23",
    "ddddwww_internalDocumentInformation_lineDetails_quantity": 136,
    "ddddwww_internalDocumentInformation_lineDetails_unitOfMeasure": "each",
    "ddddwww_internalDocumentInformation_lineDetails_money.duePayablemoney": 957.86,
    "ddddwww_internalDocumentInformation_lineDetails_money.discountAppliedmoneys_model.code": "dvbnqwe",
    "ddddwww_internalDocumentInformation_lineDetails_money.discountAppliedmoneys_model.proprietary": "rqazloy",
    "ddddwww_internalDocumentInformation_lineDetails_money.discountAppliedmoneys_money": 216.2,
    "ddddwww_internalDocumentInformation_lineDetails_money.valuemoneys_model.code": "YUIO",
    "ddddwww_internalDocumentInformation_lineDetails_money.valuemoneys_model.proprietary": "BHRTY",
    "ddddwww_internalDocumentInformation_lineDetails_money.valuemoneys_money": 391.41,
    "ddddwww_internalDocumentInformation_lineDetails_money.adjustmentmoneyAndReasons_money": 824.54,
    "ddddwww_internalDocumentInformation_lineDetails_money.adjustmentmoneyAndReasons_reason": "BONUS",
    "ddddwww_internalDocumentInformation_lineDetails_money.debittedmoney": 660.7,
    "ddddwww_internalDocumentInformation_lineDetails_money.creditNotemoney": 985.63,
    "ddddwww_internalDocumentInformation_internalDocumentmoney.duePayablemoney": 567.45,
    "ddddwww_internalDocumentInformation_internalDocumentmoney.discountAppliedmoneys_model.code": "DD",
    "ddddwww_internalDocumentInformation_internalDocumentmoney.discountAppliedmoneys_model.proprietary": "EE",
    "ddddwww_internalDocumentInformation_internalDocumentmoney.discountAppliedmoneys_money": 5.64,
    "ddddwww_internalDocumentInformation_internalDocumentmoney.valuemoneys_model.code": "z",
    "ddddwww_internalDocumentInformation_internalDocumentmoney.valuemoneys_model.proprietary": "a",
    "ddddwww_internalDocumentInformation_internalDocumentmoney.valuemoneys_money": 145,
    "ddddwww_internalDocumentInformation_internalDocumentmoney.adjustmentmoneyAndReasons_money": 678,
    "ddddwww_internalDocumentInformation_internalDocumentmoney.adjustmentmoneyAndReasons_reason": "tyuiop",
    "ddddwww_internalDocumentInformation_internalDocumentmoney.debittedmoney": 123,
    "ddddwww_internalDocumentInformation_internalDocumentmoney.creditNotemoney": 456,
    "ddddwww_supplierReferenceInformation.model.code": "x",
    "ddddwww_supplierReferenceInformation.model.proprietary": "y",
    "ddddwww_supplierReferenceInformation.issuer": "issuer",
    "ddddwww_supplierReferenceInformation.reference": "hfhjfdozkdfl;fdko;k",
    "ddddwww_billr.name": "jdjaiofjiosJOfjaiodjoiwaj",
    "ddddwww_billr.companyIdentifications_identification": "74747435438",
    "ddddwww_billr.companyIdentifications_model": "jdidfjdsjf",
    "ddddwww_bille.name": "djhsaijdwjadfja;lMEjknEAKDLJOJRF",
    "ddddwww_bille.companyIdentifications_identification": "mkskfsajdwiojdijRUWa",
    "ddddwww_bille.companyIdentifications_model": "kksjdadawx",
    "ddddwww_additionalddddwww[0]": "JDSJAHDJKLJHRFQWJESJqiorwjd",
    "ddddwww_additionalddddwww[1]": "xnjasndfjafnlkNDflkhlfkacmakjhfncasklnf",
    "chargesInformation": []
}

I have updated the request


问:
Why I can't pass string literals to const char* const& in this specialized function template
Why pass a string literal to const char* const& in a specialized function template is illegal, while to const char* is legal?

Here's the thing. There are two excercises about template specialization in C++ Primer:

Exercise 16.63: Define a function template to count the number of
occurrences of a given value in a vector. Test your program by passing it a
vector of doubles, a vector of ints, and a vector of strings.

Exercise 16.64: Write a specialized version of the template from the
previous exercise to handle vector<const char*> and a program that
uses this specialization.

The code below is my answer, the compile error appears when I pass the string literal to this specialized count function.

```<code>// Count the number of occurrences of a given value in a vector
template <typename T>
std::size_t count(const std::vector<T>& vec, const T& value)
{
    std::size_t i = 0;
    for (const auto& v : vec) {
        if (v == value)
            ++i;
    }
    return i;
}

// A specialized version where T = const char*
template <>
std::size_t count(const std::vector<const char*>& vec, const char* const& value)
{
    std::size_t i = 0;
    for (const auto& v : vec) {
        if (!strcmp(v, value))
            ++i;
    }
    return i;
}

int main()
{
    std::vector<const char*> sVec{ "cpp", "primer", "cpp", "fifth", "edition", "Cpp", "cpp" };

    // Error message: no instance of function template "count" matches the argument list,
    // argument types are: (std::vector<const char *, std::allocator<const char *>>, const char [4])
    std::cout << count(sVec, "cpp") << std::endl;

    return 0;
}
</code>```

Besides, it's perfectly ok to pass a string literal to const char* const& in a nontemplate function, which makes me confused.

```<code>void test(const char* const& str)
{
    std::cout << str << std::endl;
}

int main()
{
    test("cpp"); // Prints "cpp" as expected
    return 0;
}
</code>```

答:
You don't "pass to a function template specialization". The call is deduced against the original template definition (regardless of any specialization), deducing a type if successful.  Then if a specialization exists for the deduced type then that will be called.

The error message is about type deduction failing . You should see the exact same error even if you delete the specialization.

The type deduction fails because T occurs in two different parameters but the result of deduction differs for each parameter:

Deducing vector<T>& vec against vector<const char *> produces T=const char *

Deducing const T& value against "cpp" produces T=const char[4] .

Deduction only succeeds if all instances of T being deduced produce the same type.  There is no extra step of different types being reconciled by considering available conversions.

One way to solve the problem would be to use overloading instead of specialization (i.e. delete the text template <>).  Then there is an overload set consisting of the non-template function, and the result of deduction (if any). If deduction fails , as it does, it is not an error because the overload set still contains something.

Body:
Why pass a string literal to const char* const& in a specialized function template is illegal, while to const char* is legal?

Here's the thing. There are two excercises about template specialization in C++ Primer:

Exercise 16.63: Define a function template to count the number of
occurrences of a given value in a vector. Test your program by passing it a
vector of doubles, a vector of ints, and a vector of strings.

Exercise 16.64: Write a specialized version of the template from the
previous exercise to handle vector<const char*> and a program that
uses this specialization.

The code below is my answer, the compile error appears when I pass the string literal to this specialized count function.

// Count the number of occurrences of a given value in a vector
template <typename T>
std::size_t count(const std::vector<T>& vec, const T& value)
{
    std::size_t i = 0;
    for (const auto& v : vec) {
        if (v == value)
            ++i;
    }
    return i;
}

// A specialized version where T = const char*
template <>
std::size_t count(const std::vector<const char*>& vec, const char* const& value)
{
    std::size_t i = 0;
    for (const auto& v : vec) {
        if (!strcmp(v, value))
            ++i;
    }
    return i;
}

int main()
{
    std::vector<const char*> sVec{ "cpp", "primer", "cpp", "fifth", "edition", "Cpp", "cpp" };

    // Error message: no instance of function template "count" matches the argument list,
    // argument types are: (std::vector<const char *, std::allocator<const char *>>, const char [4])
    std::cout << count(sVec, "cpp") << std::endl;

    return 0;
}

Besides, it's perfectly ok to pass a string literal to const char* const& in a nontemplate function, which makes me confused.

void test(const char* const& str)
{
    std::cout << str << std::endl;
}

int main()
{
    test("cpp"); // Prints "cpp" as expected
    return 0;
}


问:
Randomize Users in a Voice Channel (discord.js v12)
I am trying to randomize users into two teams, team 1 and team 2. However, in some scenarios it repeats the same user on both teams.

For example:

Team 1: User 1

Team 2: User 1

The same user would be present on both teams instead of the other users' in the voice channel.

Is there a way to not present the same user twice or just once on one team.

```<code>try {

let users = message.member.voice.channel.members.map(member => `<@${member.user.id}>`)

                        let team1 = users.sort(() => Math.random() - 0.5).slice(0, Math.floor(users.length / 2))
                        let team2 = users.sort(() => Math.random() - 0.5).slice(Math.floor(users.length / 2))

                        const embed = new MessageEmbed()
                            .setTitle("Teams Created")
                            .setDescription(`Team 1: ${team1.join(', ')}\nTeam 2: ${team2.join(', ')}`)
                            .setColor("#36393E")
                            .setTimestamp()

                        message.channel.send(embed)

                    } catch (error) {
                        console.log(error)
                        const errorembed = new MessageEmbed()
                            .setTitle("⚙ Error")
                            .setDescription(`An error has occured. Please try again`)
                            .setColor("#36393E")
                            .setFooter("If this error has occured multiple times, please contact the developer.")
                            .setTimestamp()
                        await message.channel.send("There was an error. Please try again.")
                    }
</code>```

答:
Once you have filled team1, you shouldn't users.sort() again, because once the first team is defined, the second one is also defined. If you sort again, you are giving the chance for that to happen. You just have to put in team2 the users that are not in team1.

```<code>let team2=users.filter(!(user=> team1.includes(user)));
</code>```

I dont know right now if that line is correct, but it should be something like that.

Body:
I am trying to randomize users into two teams, team 1 and team 2. However, in some scenarios it repeats the same user on both teams.

For example:

Team 1: User 1

Team 2: User 1

The same user would be present on both teams instead of the other users' in the voice channel.

Is there a way to not present the same user twice or just once on one team.

try {

let users = message.member.voice.channel.members.map(member => `<@${member.user.id}>`)

                        let team1 = users.sort(() => Math.random() - 0.5).slice(0, Math.floor(users.length / 2))
                        let team2 = users.sort(() => Math.random() - 0.5).slice(Math.floor(users.length / 2))

                        const embed = new MessageEmbed()
                            .setTitle("Teams Created")
                            .setDescription(`Team 1: ${team1.join(', ')}\nTeam 2: ${team2.join(', ')}`)
                            .setColor("#36393E")
                            .setTimestamp()

                        message.channel.send(embed)

                    } catch (error) {
                        console.log(error)
                        const errorembed = new MessageEmbed()
                            .setTitle("⚙ Error")
                            .setDescription(`An error has occured. Please try again`)
                            .setColor("#36393E")
                            .setFooter("If this error has occured multiple times, please contact the developer.")
                            .setTimestamp()
                        await message.channel.send("There was an error. Please try again.")
                    }

Body:
Once you have filled team1, you shouldn't users.sort() again, because once the first team is defined, the second one is also defined. If you sort again, you are giving the chance for that to happen. You just have to put in team2 the users that are not in team1.

let team2=users.filter(!(user=> team1.includes(user)));

I dont know right now if that line is correct, but it should be something like that.


问:
[Dart]-what datra type is this list
If I'm to create a list as below,

```<code>      "quizz_answer": [
            {
              "option_id": 1,
              "is_selected": false
            },
            {
              "option_id": 2,
              "is_selected": true
            },
            {
              "option_id": 3,
              "is_selected": true
            },
            {
              "option_id": 4,
              "is_selected": false
            },
        ],
</code>```

can you tell me what data type the list should be

答:
You can use json_serializable. Create some Dart object and convert them in to json.

And freezed is better too.

Here is an article show you how to use code generation and json serialize in dart.

Title: [Dart]-what datra type is this list

Body:
If I'm to create a list as below,

      "quizz_answer": [
            {
              "option_id": 1,
              "is_selected": false
            },
            {
              "option_id": 2,
              "is_selected": true
            },
            {
              "option_id": 3,
              "is_selected": true
            },
            {
              "option_id": 4,
              "is_selected": false
            },
        ],

can you tell me what data type the list should be