问:
How to get Firebase collection data as dictionary in Swift
I want to read data from Firebase and return the output as a Dict to my ViewController.
I did not manage to get the data returned in a valid way.

This is how I read the data:

```<code>  func getCollectionData()  -> Dictionary<String, String> {
        var returnValue: String = ""

        db.collection(user).getDocuments() { (querySnapshot, err) in

            if let err = err {
                print("Error getting documents: \(err)")
                returnValue = ""
            } else {
                for document in querySnapshot!.documents {

                    let returnValue = document.data() as? Dictionary<String, String>
                    print (returnValue)
                }
            }

        }
        return returnValue
    }

</code>```

Error:

```<code>Cannot convert return expression of type 'String' to return type 'Dictionary<String, String>'
</code>```

Why is returnValue String again?
I fiddled around a lot, but never found a solution, to return the data in a good way.

The output of print(returnValue) shows it's a dictionary

```<code>Optional(["url": "https://firebasestorage.googleapis.com:443/v0/b/.....9c5e73f", "email": "a@b.com"])
</code>```

In my ViewController I want to use the data to fill a tableView:

```<code> func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = Array(myReturnedDict.values)[indexPath.row]
        return cell
    }
</code>```

EDIT:

I still get an empty Dictionary back as a returned value:

```<code>func getCollectionData()  -> Dictionary<String, String> {
        var returnValue = [String: String]()

        db.collection(user).getDocuments() { (querySnapshot, err) in

            if let err = err {
                print("Error getting documents: \(err)")
                returnValue = ["No":"data"]
            } else {
                for document in querySnapshot!.documents {
                    print (user)

                    returnValue = (document.data() as? Dictionary<String, String>)!

                    //print (returnValue)

                }
            }

        }
        return returnValue
}
</code>```

Can somebody help me?

答:
```<code>func getCollectionData(callback: @escaping(Dictionary<String, String>)  -> Void {
        db.collection(user).getDocuments() { (querySnapshot, err) in

            if let err = err {
                print("Error getting documents: \(err)")
                callback(["No":"data"])
                return
            } else {
                for document in querySnapshot!.documents {
                    callback((document.data() as? Dictionary<String, String>)!)
                }
            }
        }
}
</code>```

Body:
I want to read data from Firebase and return the output as a Dict to my ViewController.
I did not manage to get the data returned in a valid way.

This is how I read the data:

  func getCollectionData()  -> Dictionary<String, String> {
        var returnValue: String = ""

        db.collection(user).getDocuments() { (querySnapshot, err) in

            if let err = err {
                print("Error getting documents: \(err)")
                returnValue = ""
            } else {
                for document in querySnapshot!.documents {

                    let returnValue = document.data() as? Dictionary<String, String>
                    print (returnValue)
                }
            }

        }
        return returnValue
    }

Error:

Cannot convert return expression of type 'String' to return type 'Dictionary<String, String>'

Why is returnValue String again?
I fiddled around a lot, but never found a solution, to return the data in a good way.

The output of print(returnValue) shows it's a dictionary

Optional(["url": "https://firebasestorage.googleapis.com:443/v0/b/.....9c5e73f", "email": "a@b.com"])

In my ViewController I want to use the data to fill a tableView:

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = Array(myReturnedDict.values)[indexPath.row]
        return cell
    }

EDIT:

I still get an empty Dictionary back as a returned value:

func getCollectionData()  -> Dictionary<String, String> {
        var returnValue = [String: String]()

        db.collection(user).getDocuments() { (querySnapshot, err) in

            if let err = err {
                print("Error getting documents: \(err)")
                returnValue = ["No":"data"]
            } else {
                for document in querySnapshot!.documents {
                    print (user)

                    returnValue = (document.data() as? Dictionary<String, String>)!

                    //print (returnValue)

                }
            }

        }
        return returnValue
}

Can somebody help me?


来源: stackexchange

问:
Memory visualisation for C++ linux app
I am looking for a tool that would help visualize the memory usage of an application and show what's using up most of the memory - i.e. what classes, how many objects, etc. There's a similar thread that discusses the same issue for windows but I need to do this on linux.</p>

答:
You'll want to use the Valgrind tool massif (which is the documented you've linked to).  It  periodically takes snapshots of your heap and produces a full stack trace of which lines of code are responsible for what percentage of heap allocations.

example.cpp:

```<code>struct Int_1 { int a; };
struct Int_2 { int a,b; };
struct Int_3 { int a,b,c; };
struct Int_4 { int a,b,c,d; };

int main(void)
{
    for(int i = 0; i < 1000; ++i)
    {
        new Int_1(); // Line 10
        new Int_2(); // Line 11
        new Int_3(); // Line 12
        new Int_4(); // Line 13
    }
    return 0;
}
</code>```

You'll want to compile it with debug symbols so that massif can give you exact line numbers:

```<code>g++ -g example.cpp
</code>```

Now run it under Valgrind-Massif:

```<code>valgrind --tool=massif ./a.out
</code>```

This will produce a file massif.out.PID, with periodic snapshots that look like this:

```<code>#-----------
snapshot=59
#-----------
time=1487054
mem_heap_B=38384
mem_heap_extra_B=53752
mem_stacks_B=0
heap_tree=detailed
n4: 38384 (heap allocation functions) malloc/new/new[], --alloc-fns, etc.
 n0: 15344 0x4005C3: main (MemExample.cpp:13)
 n0: 11520 0x4005B1: main (MemExample.cpp:12)
 n0: 7680 0x40059F: main (MemExample.cpp:11)
 n0: 3840 0x40058D: main (MemExample.cpp:10)
</code>```

The output is interpreted as "At arbitrary time unit 1487054, there were 38384 bytes allocated on the heap".  The indentation represents a hierarchical breakdown of those 38348 bytes, which you can observe the proportions to match up with the given structure sizes.  With more complicated code you would see full call chains that include more methods and constructors.

The idea then is that the number of bytes next to a constructor in this output shows how many instances of that class were allocated through that particular stack trace, e.g.: Line 10 allocated 3840 bytes, which is a construction of Int_1 objects so at this point in time there were 960 instances.

ContentLicense: CC BY-SA 3.0

Title: Memory visualisation for C++ linux app

Body:
You'll want to use the Valgrind tool massif (which is the documented you've linked to).  It  periodically takes snapshots of your heap and produces a full stack trace of which lines of code are responsible for what percentage of heap allocations.

example.cpp:

struct Int_1 { int a; };
struct Int_2 { int a,b; };
struct Int_3 { int a,b,c; };
struct Int_4 { int a,b,c,d; };

int main(void)
{
    for(int i = 0; i < 1000; ++i)
    {
        new Int_1(); // Line 10
        new Int_2(); // Line 11
        new Int_3(); // Line 12
        new Int_4(); // Line 13
    }
    return 0;
}

You'll want to compile it with debug symbols so that massif can give you exact line numbers:

g++ -g example.cpp

Now run it under Valgrind-Massif:

valgrind --tool=massif ./a.out

This will produce a file massif.out.PID, with periodic snapshots that look like this:

#-----------
snapshot=59
#-----------
time=1487054
mem_heap_B=38384
mem_heap_extra_B=53752
mem_stacks_B=0
heap_tree=detailed
n4: 38384 (heap allocation functions) malloc/new/new[], --alloc-fns, etc.
 n0: 15344 0x4005C3: main (MemExample.cpp:13)
 n0: 11520 0x4005B1: main (MemExample.cpp:12)
 n0: 7680 0x40059F: main (MemExample.cpp:11)
 n0: 3840 0x40058D: main (MemExample.cpp:10)

The output is interpreted as "At arbitrary time unit 1487054, there were 38384 bytes allocated on the heap".  The indentation represents a hierarchical breakdown of those 38348 bytes, which you can observe the proportions to match up with the given structure sizes.  With more complicated code you would see full call chains that include more methods and constructors.

The idea then is that the number of bytes next to a constructor in this output shows how many instances of that class were allocated through that particular stack trace, e.g.: Line 10 allocated 3840 bytes, which is a construction of Int_1 objects so at this point in time there were 960 instances.


问:
Is there a way to add CORS rule to Terraform aws_s3_bucket data source?
I have an existing bucket that was not created via Terraform. I'm currently setting a policy on that bucket for additional access rights. I need to add a cors_rule to the bucket, but everything I'm finding suggests that you need to create the resource in order to add the cors rule. Is there a way to add a cors_rule to an existing bucket data source?

Adding CORS to a bucket that's being created: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/s3_bucket#using-cors

Documentation on the bucket data source: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/s3_bucket

```<code>data "aws_s3_bucket" "my_bucket" {
  bucket = "my-bucket"

  # This produces a failure on plan
  cors_rule {
    allowed_headers = ["*"]
    allowed_methods = ["GET", "HEAD"]
    allowed_origins = [
      "https://example.my-website.com"
    ]
    expose_headers  = [
      "Access-Control-Allow-Origin",
      "ETag"
    ]
    max_age_seconds = 3000
  }
}

resource "aws_s3_bucket_policy" "allow_access" {
  bucket = data.aws_s3_bucket.my_bucket.id
  policy = data.aws_iam_policy_document.allow_access.json
}

data "aws_iam_policy_document" "allow_access" {
  statement {
    sid = "Access"

    principals {
      type = "AWS"
      identifiers = ["arn:aws:iam::123456789012:user/test"]
    }

    actions = [
      "s3:GetObject",
      "s3:GetBucketLocation",
      "s3:ListBucket",
    ]

    resources = [
      data.aws_s3_bucket.my_bucket.arn,
      "${data.aws_s3_bucket.my_bucket.arn}/*"
    ]
  }
}
</code>```

答:
You can only modify resources that are managed by terraform, not resources brought in as a data source. What you can do is create a resource for your bucket, and then import the existing bucket:

```<code>terraform import aws_s3_bucket.my_bucket my-bucket
</code>```

The import command will give you a list of all properties set on the bucket. For properties you don't want to manage with terraform, use the ignore argument on the lifecycle block.

ContentLicense: CC BY-SA 4.0

Body:
I have an existing bucket that was not created via Terraform. I'm currently setting a policy on that bucket for additional access rights. I need to add a cors_rule to the bucket, but everything I'm finding suggests that you need to create the resource in order to add the cors rule. Is there a way to add a cors_rule to an existing bucket data source?

Adding CORS to a bucket that's being created: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/s3_bucket#using-cors

Documentation on the bucket data source: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/s3_bucket

data "aws_s3_bucket" "my_bucket" {
  bucket = "my-bucket"

  # This produces a failure on plan
  cors_rule {
    allowed_headers = ["*"]
    allowed_methods = ["GET", "HEAD"]
    allowed_origins = [
      "https://example.my-website.com"
    ]
    expose_headers  = [
      "Access-Control-Allow-Origin",
      "ETag"
    ]
    max_age_seconds = 3000
  }
}

resource "aws_s3_bucket_policy" "allow_access" {
  bucket = data.aws_s3_bucket.my_bucket.id
  policy = data.aws_iam_policy_document.allow_access.json
}

data "aws_iam_policy_document" "allow_access" {
  statement {
    sid = "Access"

    principals {
      type = "AWS"
      identifiers = ["arn:aws:iam::123456789012:user/test"]
    }

    actions = [
      "s3:GetObject",
      "s3:GetBucketLocation",
      "s3:ListBucket",
    ]

    resources = [
      data.aws_s3_bucket.my_bucket.arn,
      "${data.aws_s3_bucket.my_bucket.arn}/*"
    ]
  }
}

Body:
You can only modify resources that are managed by terraform, not resources brought in as a data source. What you can do is create a resource for your bucket, and then import the existing bucket:

terraform import aws_s3_bucket.my_bucket my-bucket

The import command will give you a list of all properties set on the bucket. For properties you don't want to manage with terraform, use the ignore argument on the lifecycle block.


问:
Not able to hit the meteor app server using Jmeter
Required a quick help.

I am preparing a load testing script in jmeter which is hitting the meteor app server.

The problem is that, all the requests are executing without any error but in the server we have a option to see how many request are being hit to the server ,but that counter is not increasing and not able to hit the request.

so in above image you can see the connection tab which shows the no. of user currently active, i am hitting more than 50 users but still counter is not getting increased.

答:
Your forgot to share your Thread Group configuration but looking at my crystal ball I can assume that you have only 1 iteration so each virtual users executes a Sampler (or Samplers) and is being shut down.

If you want concurrency - you need to set higher number of iterations so the users which have been started already would continue holding the load while others are ramping up, example setup:

More information: JMeter Test Results: Why the Actual Users Number is Lower than Expected


问:
Making combinations
I am a beginner in Python and I need a help with this task:

I have a a list with unknown number of characters that have a following form:

my_list = ["t1v1", "t1v2", "t2v1", "t2v2", "t2v3"]
```
<p><code>t</code> stands for a test and <code>v</code> stands for a version of the test. I would like to get all possible combinations between tests. In this case I will have 2x3=6 combinations of tests.</p>
<pre class="lang-py prettyprint-override"><code>combinations = ["t1v1_t2v1", "t1v1_t2v2", "t1v1_t2v3", "t1v2_t2v1", "t1v2_t2v2", "t1v2_t2v3"]
</code>```

I cannot make combinations within a test, for example "t1v1_t1v2"is not possible. Moreover, I can have more tests, not just two as in this example.

How can I do this, please?

答:
You can use itertools.product for this. The following code should work for any number of tests:

```<code>from itertools import product, groupby

tests = ["t1v1", "t1v2", "t2v1", "t2v2", "t2v3", "t3v1", "t3v2"]
# group the lists into lists of lists containing items of single test
lists = [list(l) for _, l in groupby(tests, lambda x: x[:2])]
output = list('_'.join(x) for x in product(*lists))
</code>```

here output is -

```<code>['t1v1_t2v1_t3v1', 't1v1_t2v1_t3v2', 't1v1_t2v2_t3v1', 't1v1_t2v2_t3v2', 't1v1_t2v3_t3v1', 't1v1_t2v3_t3v2', 't1v2_t2v1_t3v1', 't1v2_t2v1_t3v2', 't1v2_t2v2_t3v1', 't1v2_t2v2_t3v2', 't1v2_t2v3_t3v1', 't1v2_t2v3_t3v2']
</code>```

Title: Making combinations

Body:
I am a beginner in Python and I need a help with this task:

I have a a list with unknown number of characters that have a following form:

my_list = ["t1v1", "t1v2", "t2v1", "t2v2", "t2v3"]

t stands for a test and v stands for a version of the test. I would like to get all possible combinations between tests. In this case I will have 2x3=6 combinations of tests.

combinations = ["t1v1_t2v1", "t1v1_t2v2", "t1v1_t2v3", "t1v2_t2v1", "t1v2_t2v2", "t1v2_t2v3"]

I cannot make combinations within a test, for example "t1v1_t1v2"is not possible. Moreover, I can have more tests, not just two as in this example.

How can I do this, please?

Body:
You can use itertools.product for this. The following code should work for any number of tests:

from itertools import product, groupby

tests = ["t1v1", "t1v2", "t2v1", "t2v2", "t2v3", "t3v1", "t3v2"]
# group the lists into lists of lists containing items of single test
lists = [list(l) for _, l in groupby(tests, lambda x: x[:2])]
output = list('_'.join(x) for x in product(*lists))

here output is -

['t1v1_t2v1_t3v1', 't1v1_t2v1_t3v2', 't1v1_t2v2_t3v1', 't1v1_t2v2_t3v2', 't1v1_t2v3_t3v1', 't1v1_t2v3_t3v2', 't1v2_t2v1_t3v1', 't1v2_t2v1_t3v2', 't1v2_t2v2_t3v1', 't1v2_t2v2_t3v2', 't1v2_t2v3_t3v1', 't1v2_t2v3_t3v2']


问:
List of list of dicts values to list in python
The order of the resulted list is irrelevant, I need to add the elements afterwards.</p>
```<code>Input1: [[{'a': 57}], 87]
Expect Output1: [57,87]

Input2: [[{'a': 57, 'b':12}], 87]
Expect Output2: [57,12,87]

Input3: [[{'a': 57}], 12, [{'a':34}], 87]
Expect Output3: [57,12,34,87]
</code>```

答:
That's Pretty Simple all you Need is to just check the Type of the object

Then If it's a list get the first index of it which is a dict

So for example if i have
[{1,2,3}]
It will convert it to Just {1,2,3}

Then Looping Through The values(not the keys) in the Dict
and just adds it to a list

Whereas If it's not a list then just add it to the list

Input3 = [[{'a': 57}], 12, [{'a':34}], 87]

li = []

for i in Input3:
    if type(i) == list:
        for item in i[0].values():
            li.append(item)

    else:
        li.append(i)
```

Body:
The order of the resulted list is irrelevant, I need to add the elements afterwards.

Input1: [[{'a': 57}], 87]
Expect Output1: [57,87]

Input2: [[{'a': 57, 'b':12}], 87]
Expect Output2: [57,12,87]

Input3: [[{'a': 57}], 12, [{'a':34}], 87]
Expect Output3: [57,12,34,87]


问:
Zip multiple arrays in PHP based on their identical keys and not their indices or their positions in array
I have two arrays:

```<code>$a = ['one'=>1,'two'=> 2,'three'=> 3,'four'=> 4,'five'=> 5, 'six' => 6];
$b = ['one'=>'uno', 'three'=>'tres','two'=> 'dos', 'four'=>'cuatro', 'five'=>'cinco'];
</code>```

note that in $b Array 'three' and 'two' keys are not in same order as $a. also 'six' key is not available in $b Array.

I want this result as output:

```<code>Array
(
    [0] => Array
        (
            [0] => 1
            [1] => uno
        )

    [1] => Array
        (
            [0] => 2
            [1] => dos
        )

    [2] => Array
        (
            [0] => 3
            [1] => tres
        )

    [3] => Array
        (
            [0] => 4
            [1] => cuatro
        )

    [4] => Array
        (
            [0] => 5
            [1] => cinco
        )

)
</code>```

I tried to use array_map but it don't detect keys and just zip them based of their indices:

```<code>$d = array_map(null, $a, $b);
</code>```

答:
An example using foreach

<?php

$a = ['one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, 'five' => 5];
$b = ['one' => 'uno', 'three' => 'tres', 'two' => 'dos', 'four' => 'cuatro', 'five' => 'cinco'];

$output = [];

foreach ($a as $key => $value) {
    $output[] = [$value,  $b[$key]];
}

print_r($output);
```

Body:
I have two arrays:

$a = ['one'=>1,'two'=> 2,'three'=> 3,'four'=> 4,'five'=> 5, 'six' => 6];
$b = ['one'=>'uno', 'three'=>'tres','two'=> 'dos', 'four'=>'cuatro', 'five'=>'cinco'];

note that in $b Array 'three' and 'two' keys are not in same order as $a. also 'six' key is not available in $b Array.

I want this result as output:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => uno
        )

    [1] => Array
        (
            [0] => 2
            [1] => dos
        )

    [2] => Array
        (
            [0] => 3
            [1] => tres
        )

    [3] => Array
        (
            [0] => 4
            [1] => cuatro
        )

    [4] => Array
        (
            [0] => 5
            [1] => cinco
        )

)

I tried to use array_map but it don't detect keys and just zip them based of their indices:

$d = array_map(null, $a, $b);


问:
Font size in animation using Python
How do I increase the font size of the numbers in the heatmap as well as the colorbar? The numbers are too small as can be seen below.

```<code>import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from celluloid import Camera

a = np.array([[0.31131114, 0.96641729, 0.72632796],
       [0.42412489, 0.66088661, 0.60893906],
       [0.64454019, 0.509509  , 0.66285615]])

b = np.array([0.31131114, 0.42412489, 0.509509  , 0.64454019])

fig, (ax1, cbar_ax) = plt.subplots(ncols=2, gridspec_kw={'width_ratios': [20, 2]},
                                   figsize=(25,25))
camera = Camera(fig)
sns.set_style('white')
rectangles = []
for bb in b.flatten():
    sns.heatmap(a, linewidth=2, ax=ax1, annot=True, cbar_ax=cbar_ax)
    rectangles.append(plt.Rectangle((np.where(a == bb)[1][0], np.where(a == bb)[0][0]), 1,1,
                                    fc='green', ec='green', lw=5, clip_on=False))
    for rect in rectangles:
        ax1.add_patch(rect)
    camera.snap()

animation = camera.animate(interval=800)
animation.save('Today_3x3.gif')
plt.show()
</code>```

答:
Adjust your figure size so that it's smaller (so your text, relatively, is bigger)

or

Scale up the SNS font sizes using sns.set(font_scale=3) (credit @JohanC)

Title: Font size in animation using Python

Body:
How do I increase the font size of the numbers in the heatmap as well as the colorbar? The numbers are too small as can be seen below.

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from celluloid import Camera

a = np.array([[0.31131114, 0.96641729, 0.72632796],
       [0.42412489, 0.66088661, 0.60893906],
       [0.64454019, 0.509509  , 0.66285615]])

b = np.array([0.31131114, 0.42412489, 0.509509  , 0.64454019])

fig, (ax1, cbar_ax) = plt.subplots(ncols=2, gridspec_kw={'width_ratios': [20, 2]},
                                   figsize=(25,25))
camera = Camera(fig)
sns.set_style('white')
rectangles = []
for bb in b.flatten():
    sns.heatmap(a, linewidth=2, ax=ax1, annot=True, cbar_ax=cbar_ax)
    rectangles.append(plt.Rectangle((np.where(a == bb)[1][0], np.where(a == bb)[0][0]), 1,1,
                                    fc='green', ec='green', lw=5, clip_on=False))
    for rect in rectangles:
        ax1.add_patch(rect)
    camera.snap()

animation = camera.animate(interval=800)
animation.save('Today_3x3.gif')
plt.show()


问:
df.drop does not work properly, pandas python
I have this excel file that I would like to "normalize" with the below code by dropping the A and B columns and then dropping the Rows 1,2,3,5 and making the  row 4 as header.

```<code>df_weekly = pd.read_excel('Run_report.xlsm', sheet_name= "weekly")
df_weekly = df_weekly.drop(df_weekly.columns[[0,1]], axis=1)
df_weekly = df_weekly.drop(df_weekly.index[[0,1,2,4]])

print(df_weekly.head(8))
</code>```

But I keep getting this weird df that I dont understand the reason why

```<code>Unnamed: 2 Unnamed: 3  ...    Unnamed: 53 Unnamed: 54
3         NaN        NaN  ...            NaN         NaN
5        EU01         10  ...  5400537629432         NaN
6        EU01         10  ...  5400599118677         NaN
7        EU01         10  ...  5400599027382         NaN
8        EU01         10  ...  5400599028730         NaN
9        EU01         10  ...  5400599028761         NaN
10       EU01         10  ...  5400599613554         NaN
11       EU01         10  ...  5400599028945
</code>```

Also:

```<code>top= df_weekly.columns.values.tolist()
print(top)

['Unnamed: 2', 'Unnamed: 3', 'Unnamed: 4', 'Unnamed: 5', 'Unnamed: 6', 'Unnamed: 7', 'Unnamed: 8',....]
</code>```

答:
You must explicitely set the column names:</p>
```<code>df_weekly = pd.read_excel('Run_report.xlsm', sheet_name= "weekly",
                          header=None)
df_weekly = df_weekly.drop(df_weekly.columns[[0,1]], axis=1)
df_weekly.columns = df_weekly.loc[3].rename(None)
df_weekly = df_weekly.drop(range(5))

print(df_weekly.head(8))
</code>```

Body:
I have this excel file that I would like to "normalize" with the below code by dropping the A and B columns and then dropping the Rows 1,2,3,5 and making the  row 4 as header.

df_weekly = pd.read_excel('Run_report.xlsm', sheet_name= "weekly")
df_weekly = df_weekly.drop(df_weekly.columns[[0,1]], axis=1)
df_weekly = df_weekly.drop(df_weekly.index[[0,1,2,4]])

print(df_weekly.head(8))

But I keep getting this weird df that I dont understand the reason why

Unnamed: 2 Unnamed: 3  ...    Unnamed: 53 Unnamed: 54
3         NaN        NaN  ...            NaN         NaN
5        EU01         10  ...  5400537629432         NaN
6        EU01         10  ...  5400599118677         NaN
7        EU01         10  ...  5400599027382         NaN
8        EU01         10  ...  5400599028730         NaN
9        EU01         10  ...  5400599028761         NaN
10       EU01         10  ...  5400599613554         NaN
11       EU01         10  ...  5400599028945

Also:

top= df_weekly.columns.values.tolist()
print(top)

['Unnamed: 2', 'Unnamed: 3', 'Unnamed: 4', 'Unnamed: 5', 'Unnamed: 6', 'Unnamed: 7', 'Unnamed: 8',....]

Body:
You must explicitely set the column names:

df_weekly = pd.read_excel('Run_report.xlsm', sheet_name= "weekly",
                          header=None)
df_weekly = df_weekly.drop(df_weekly.columns[[0,1]], axis=1)
df_weekly.columns = df_weekly.loc[3].rename(None)
df_weekly = df_weekly.drop(range(5))

print(df_weekly.head(8))


问:
Programmatically interacting with gdb using java
I'm writing an application that uses GDB to access information through java.

Using Runtime.getRuntime.exec, I'm able to attach GDB to any processes.

The problem is that I am unable to send inputs to GDB after it has been started.

**EDIT (19/8/2011):

At the line "out.println(gdbcommand)", gdb is started. How do I get the stdout of the newly spawned gdb, write inputs to it and then read the stdin. So far, I'm only able get the output up till "out.println(gdbcommand)". All attempts at trying to programmatically send inputs to gdb have not been working so far.**

Refer to trojanfoe's comments below my question.
Below is an edited sample of my code:

```<code>try {
    String gdbcommand = "/data/bin/gdb " + pidS + " " + pidS;
    String line;

    Process process = Runtime.getRuntime().exec("su");

    if (process != null) {
        BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(process.getOutputStream())),true);

        out.println(gdbcommand);

        //Note this line does not get sent to gdb's interface after starting gdb.
        //Is it possible to connect to the new stdout of gdb's interface?
        out.println("info registers");

        out.flush();
        out.close();

        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }

        process.destroy();
    }

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

Note that "info registers" is not sent to GDB's interface and after calling out.close(), gdb's interface quits. (As seen below)

```<code>08-18 14:40:36.595: INFO/System.out(4408): 0xafd0c51c in epoll_wait () from /system/lib/libc.so

08-18 14:40:36.595: INFO/System.out(4408): (gdb) Hangup detected on fd 0

08-18 14:40:36.595: INFO/System.out(4408): error detected on stdin

08-18 14:40:36.595: INFO/System.out(4408): The program is running.  Quit anyway (and detach it)? (y or n) [answered Y; input not from terminal]
</code>```

答:
Insread of

```<code>String[] command = {"/system/bin/sh", "-c", "su"};
</code>```

maybe do a

```<code>String[] command = {"/system/bin/sh", "-c", "/data/bin/gdb " + pidS + " " + pidS};
</code>```

or just

```<code>String[] command = {"/data/bin/gdb " + pidS + " " + pidS};
</code>```

Body:
I'm writing an application that uses GDB to access information through java.

Using Runtime.getRuntime.exec, I'm able to attach GDB to any processes.

The problem is that I am unable to send inputs to GDB after it has been started.

**EDIT (19/8/2011):

At the line "out.println(gdbcommand)", gdb is started. How do I get the stdout of the newly spawned gdb, write inputs to it and then read the stdin. So far, I'm only able get the output up till "out.println(gdbcommand)". All attempts at trying to programmatically send inputs to gdb have not been working so far.**

Refer to trojanfoe's comments below my question.
Below is an edited sample of my code:

try {
    String gdbcommand = "/data/bin/gdb " + pidS + " " + pidS;
    String line;

    Process process = Runtime.getRuntime().exec("su");

    if (process != null) {
        BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(process.getOutputStream())),true);

        out.println(gdbcommand);

        //Note this line does not get sent to gdb's interface after starting gdb.
        //Is it possible to connect to the new stdout of gdb's interface?
        out.println("info registers");

        out.flush();
        out.close();

        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }

        process.destroy();
    }

} catch (Exception e) {
    e.printStackTrace();
}

Note that "info registers" is not sent to GDB's interface and after calling out.close(), gdb's interface quits. (As seen below)

08-18 14:40:36.595: INFO/System.out(4408): 0xafd0c51c in epoll_wait () from /system/lib/libc.so

08-18 14:40:36.595: INFO/System.out(4408): (gdb) Hangup detected on fd 0

08-18 14:40:36.595: INFO/System.out(4408): error detected on stdin

08-18 14:40:36.595: INFO/System.out(4408): The program is running.  Quit anyway (and detach it)? (y or n) [answered Y; input not from terminal]

Body:
Insread of

String[] command = {"/system/bin/sh", "-c", "su"};

maybe do a

String[] command = {"/system/bin/sh", "-c", "/data/bin/gdb " + pidS + " " + pidS};

or just

String[] command = {"/data/bin/gdb " + pidS + " " + pidS};


问:
How to order the square bracket elements
I need the sort the non square bracket element in ascending and sqauare bracket element in descending.

input:

```<code>9[8] 5[18] [17]2
</code>```

output:

```<code>2[18] 5[17] [8]9
</code>```

My code:

```<code>import re
n=int(input())
l=list(map(str,input().split()))
print(l)
r = re.compile("\.|[\[-\]]")
for i in range(0,len(l)):
  l[i]=r.split(l[i])
print(l)
</code>```

I splited the elements but i don't know how to sort this proper manner If you are interested to share your thoughts I will be very happy.

Thanks in advance

答:
Easy to extract inside numbers, replace them with a non-digit marker to make extraction of the outside numbers easy as well. Sort each as desired, then fill them back in.

```<code>import re

s = '9[8] 5[18] [17]2'

inside = re.findall(r'\[(\d+)\]', s)
s = re.sub(r'\[\d+\]', '[i]', s)
outside = re.findall(r'\d+', s)

outside.sort(key=int)
inside.sort(key=int, reverse=True)
outside = iter(outside)
inside = iter(inside)

s = re.sub(r'\d+', lambda _: next(outside), s)
s = re.sub('i', lambda _: next(inside), s)

print(s)
</code>```

Try it online!

Body:
I need the sort the non square bracket element in ascending and sqauare bracket element in descending.

input:

9[8] 5[18] [17]2

output:

2[18] 5[17] [8]9

My code:

import re
n=int(input())
l=list(map(str,input().split()))
print(l)
r = re.compile("\.|[\[-\]]")
for i in range(0,len(l)):
  l[i]=r.split(l[i])
print(l)

I splited the elements but i don't know how to sort this proper manner If you are interested to share your thoughts I will be very happy.

Thanks in advance

Body:
Easy to extract inside numbers, replace them with a non-digit marker to make extraction of the outside numbers easy as well. Sort each as desired, then fill them back in.

import re

s = '9[8] 5[18] [17]2'

inside = re.findall(r'\[(\d+)\]', s)
s = re.sub(r'\[\d+\]', '[i]', s)
outside = re.findall(r'\d+', s)

outside.sort(key=int)
inside.sort(key=int, reverse=True)
outside = iter(outside)
inside = iter(inside)

s = re.sub(r'\d+', lambda _: next(outside), s)
s = re.sub('i', lambda _: next(inside), s)

print(s)

Try it online!


问:
How to get rid of warning "Creating EvaluationContext with no beanFactory"?
I'm trying to setup a dynamic IntegrationFlow to read files from a local directory. Therefore I've created the following parameterizable class:

@Configuration
public class FileConsoleFlow {

    @Bean("flowBuilderFactory")
    Function<Properties, IntegrationFlow> flowBuilderFactory() {
        return (properties) -> new SimpleFlowBuilder(properties).build();
    }

    static class SimpleFlowBuilder {

        private Properties properties;

        public FlowBuilder(Properties properties) {
            this.properties = properties;
        }

        public IntegrationFlow build() {
            return IntegrationFlows.from(localSource(), c -> c.poller(pollerMetadata()))
                    .handle(message -> System.out.println(message))
                    .get();
        }

        public FileReadingMessageSource localSource() {
            CompositeFileListFilter<File> filters = new CompositeFileListFilter<>();
            filters.addFilter(new SimplePatternFileListFilter(properties.getProperty("local-file-pattern")));
            filters.addFilter(new AcceptOnceFileListFilter<>(10000));

            RecursiveDirectoryScanner scanner = new RecursiveDirectoryScanner();
            scanner.setFilter(filters);

            FileReadingMessageSource fileSource = new FileReadingMessageSource();
            fileSource.setDirectory(new File(properties.getProperty("local-directory")));
            fileSource.setScanner(scanner);
            return fileSource;
        }

        public PollerMetadata pollerMetadata() {
            return Pollers.fixedDelay(1000)
                    .maxMessagesPerPoll(100)
                    .advice(transactionInterceptor())
                    .transactionSynchronizationFactory(transactionSynchronizationFactory())
                    .get();
        }

        public TransactionInterceptor transactionInterceptor() {
            return new TransactionInterceptorBuilder()
                    .transactionManager(txManager())
                    .build();
        }

        public TransactionManager txManager() {
            return new PseudoTransactionManager();
        }

        public TransactionSynchronizationFactory transactionSynchronizationFactory() {
            ExpressionEvaluatingTransactionSynchronizationProcessor processor =
                    new ExpressionEvaluatingTransactionSynchronizationProcessor();

            SpelExpressionParser spelParser = new SpelExpressionParser();
            processor.setAfterCommitExpression(spelParser.parseExpression("payload.delete()"));
            processor.setAfterRollbackExpression(spelParser.parseExpression("payload.renameTo(new java.io.File(payload.absolutePath + '.FAILED'))"));

            return new DefaultTransactionSynchronizationFactory(processor);
        }
    }
}
```
<p>The parameterized flows are registered with the help of the <code>IntegrationFlowContext</code> as follows:</p>
<pre class="lang-java prettyprint-override"><code>...
integrationFlowContext.registration(flow)
    .autoStartup(false)
    .id("flow-" + id)
    .register();
...
integrationFlowContext.getRegistry().forEach((name, flow) -> flow.start());
</code>```

After starting up the application I get the following warning:

 2022-02-08 14:11:41.951  WARN [,1e3c4776ef54251e,1e3c4776ef54251e] 1 --- [   scheduling-1] o.s.i.expression.ExpressionUtils         : Creating EvaluationContext with no beanFactory
java.lang.RuntimeException: No beanFactory
at org.springframework.integration.expression.ExpressionUtils.createStandardEvaluationContext(ExpressionUtils.java:90) ~[spring-integration-core-5.5.8.jar:5.5.8]
    at org.springframework.integration.transaction.ExpressionEvaluatingTransactionSynchronizationProcessor.createEvaluationContext(ExpressionEvaluatingTransactionSynchronizationProcessor.java:218) ~[spring-integration-core-5.5.8.jar:5.5.8]
    at org.springframework.integration.transaction.ExpressionEvaluatingTransactionSynchronizationProcessor.prepareEvaluationContextToUse(ExpressionEvaluatingTransactionSynchronizationProcessor.java:202) ~[spring-integration-core-5.5.8.jar:5.5.8]
    at org.springframework.integration.transaction.ExpressionEvaluatingTransactionSynchronizationProcessor.doProcess(ExpressionEvaluatingTransactionSynchronizationProcessor.java:141) ~[spring-integration-core-5.5.8.jar:5.5.8]
    at org.springframework.integration.transaction.ExpressionEvaluatingTransactionSynchronizationProcessor.processAfterCommit(ExpressionEvaluatingTransactionSynchronizationProcessor.java:125) ~[spring-integration-core-5.5.8.jar:5.5.8]
    at org.springframework.integration.transaction.DefaultTransactionSynchronizationFactory$DefaultTransactionalResourceSynchronization.processResourceAfterCommit(DefaultTransactionSynchronizationFactory.java:79) ~[spring-integration-core-5.5.8.jar:5.5.8]
    at org.springframework.integration.transaction.DefaultTransactionSynchronizationFactory$DefaultTransactionalResourceSynchronization.processResourceAfterCommit(DefaultTransactionSynchronizationFactory.java:53) ~[spring-integration-core-5.5.8.jar:5.5.8]
    at org.springframework.transaction.support.ResourceHolderSynchronization.afterCommit(ResourceHolderSynchronization.java:87) ~[spring-tx-5.3.15.jar:5.3.15]
    at org.springframework.transaction.support.TransactionSynchronizationUtils.invokeAfterCommit(TransactionSynchronizationUtils.java:135) ~[spring-tx-5.3.15.jar:5.3.15]
    at org.springframework.transaction.support.TransactionSynchronizationUtils.triggerAfterCommit(TransactionSynchronizationUtils.java:123) ~[spring-tx-5.3.15.jar:5.3.15]
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.triggerAfterCommit(AbstractPlatformTransactionManager.java:936) ~[spring-tx-5.3.15.jar:5.3.15]
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:782) ~[spring-tx-5.3.15.jar:5.3.15]
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:711) ~[spring-tx-5.3.15.jar:5.3.15]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:654) ~[spring-tx-5.3.15.jar:5.3.15]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:407) ~[spring-tx-5.3.15.jar:5.3.15]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119) ~[spring-tx-5.3.15.jar:5.3.15]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.15.jar:5.3.15]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215) ~[spring-aop-5.3.15.jar:5.3.15]
    at jdk.proxy2/jdk.proxy2.$Proxy101.call(Unknown Source) ~[na:na]
    at org.springframework.integration.endpoint.AbstractPollingEndpoint.pollForMessage(AbstractPollingEndpoint.java:413) ~[spring-integration-core-5.5.8.jar:5.5.8]
    at org.springframework.integration.endpoint.AbstractPollingEndpoint.lambda$createPoller$4(AbstractPollingEndpoint.java:348) ~[spring-integration-core-5.5.8.jar:5.5.8]
    at org.springframework.integration.util.ErrorHandlingTaskExecutor.lambda$execute$0(ErrorHandlingTaskExecutor.java:57) ~[spring-integration-core-5.5.8.jar:5.5.8]
    at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50) ~[spring-core-5.3.15.jar:5.3.15]
    at org.springframework.integration.util.ErrorHandlingTaskExecutor.execute(ErrorHandlingTaskExecutor.java:55) ~[spring-integration-core-5.5.8.jar:5.5.8]
    at org.springframework.integration.endpoint.AbstractPollingEndpoint.lambda$createPoller$5(AbstractPollingEndpoint.java:341) ~[spring-integration-core-5.5.8.jar:5.5.8]
    at org.springframework.cloud.sleuth.instrument.async.TraceRunnable.run(TraceRunnable.java:64) ~[spring-cloud-sleuth-instrumentation-3.1.0.jar:3.1.0]
    at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) ~[spring-context-5.3.15.jar:5.3.15]
    at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:95) ~[spring-context-5.3.15.jar:5.3.15]
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:539) ~[na:na]
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na]
    at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:304) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635) ~[na:na]
    at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na]
```

If I understood things correctly, the IntegrationFlowContext is responsible for the creation of the integration-beans (and thus the setting of the beanFactory). But then why do I get this error message?

答:
The error means that TransactionSynchronizationFactory must be declared as a bean and therefore its BeanFactory requirements would be fulfilled.

Please, revise all your volatile objects and consider to make some of them as global singleton beans.

I believe all of these could go to the main configuration, not dynamic: PollerMetadata, TransactionInterceptor, TransactionManager and TransactionSynchronizationFactory. The dynamic part in your solution is really just that FileReadingMessageSource.

It is better to use as less dynamic as possible for better performance and proper reusability. You also would avoid duplications whenever they are not needed.

I would even move that .handle(message -> System.out.println(message)) to the separate global singleton IntegrationFlow and use only a channel reference from this one to avoid extra duplication.

Body:
I'm trying to setup a dynamic IntegrationFlow to read files from a local directory. Therefore I've created the following parameterizable class:

@Configuration
public class FileConsoleFlow {

    @Bean("flowBuilderFactory")
    Function<Properties, IntegrationFlow> flowBuilderFactory() {
        return (properties) -> new SimpleFlowBuilder(properties).build();
    }

    static class SimpleFlowBuilder {

        private Properties properties;

        public FlowBuilder(Properties properties) {
            this.properties = properties;
        }

        public IntegrationFlow build() {
            return IntegrationFlows.from(localSource(), c -> c.poller(pollerMetadata()))
                    .handle(message -> System.out.println(message))
                    .get();
        }

        public FileReadingMessageSource localSource() {
            CompositeFileListFilter<File> filters = new CompositeFileListFilter<>();
            filters.addFilter(new SimplePatternFileListFilter(properties.getProperty("local-file-pattern")));
            filters.addFilter(new AcceptOnceFileListFilter<>(10000));

            RecursiveDirectoryScanner scanner = new RecursiveDirectoryScanner();
            scanner.setFilter(filters);

            FileReadingMessageSource fileSource = new FileReadingMessageSource();
            fileSource.setDirectory(new File(properties.getProperty("local-directory")));
            fileSource.setScanner(scanner);
            return fileSource;
        }

        public PollerMetadata pollerMetadata() {
            return Pollers.fixedDelay(1000)
                    .maxMessagesPerPoll(100)
                    .advice(transactionInterceptor())
                    .transactionSynchronizationFactory(transactionSynchronizationFactory())
                    .get();
        }

        public TransactionInterceptor transactionInterceptor() {
            return new TransactionInterceptorBuilder()
                    .transactionManager(txManager())
                    .build();
        }

        public TransactionManager txManager() {
            return new PseudoTransactionManager();
        }

        public TransactionSynchronizationFactory transactionSynchronizationFactory() {
            ExpressionEvaluatingTransactionSynchronizationProcessor processor =
                    new ExpressionEvaluatingTransactionSynchronizationProcessor();

            SpelExpressionParser spelParser = new SpelExpressionParser();
            processor.setAfterCommitExpression(spelParser.parseExpression("payload.delete()"));
            processor.setAfterRollbackExpression(spelParser.parseExpression("payload.renameTo(new java.io.File(payload.absolutePath + '.FAILED'))"));

            return new DefaultTransactionSynchronizationFactory(processor);
        }
    }
}

The parameterized flows are registered with the help of the IntegrationFlowContext as follows:

...
integrationFlowContext.registration(flow)
    .autoStartup(false)
    .id("flow-" + id)
    .register();
...
integrationFlowContext.getRegistry().forEach((name, flow) -> flow.start());

After starting up the application I get the following warning:

 2022-02-08 14:11:41.951  WARN [,1e3c4776ef54251e,1e3c4776ef54251e] 1 --- [   scheduling-1] o.s.i.expression.ExpressionUtils         : Creating EvaluationContext with no beanFactory
java.lang.RuntimeException: No beanFactory
at org.springframework.integration.expression.ExpressionUtils.createStandardEvaluationContext(ExpressionUtils.java:90) ~[spring-integration-core-5.5.8.jar:5.5.8]
    at org.springframework.integration.transaction.ExpressionEvaluatingTransactionSynchronizationProcessor.createEvaluationContext(ExpressionEvaluatingTransactionSynchronizationProcessor.java:218) ~[spring-integration-core-5.5.8.jar:5.5.8]
    at org.springframework.integration.transaction.ExpressionEvaluatingTransactionSynchronizationProcessor.prepareEvaluationContextToUse(ExpressionEvaluatingTransactionSynchronizationProcessor.java:202) ~[spring-integration-core-5.5.8.jar:5.5.8]
    at org.springframework.integration.transaction.ExpressionEvaluatingTransactionSynchronizationProcessor.doProcess(ExpressionEvaluatingTransactionSynchronizationProcessor.java:141) ~[spring-integration-core-5.5.8.jar:5.5.8]
    at org.springframework.integration.transaction.ExpressionEvaluatingTransactionSynchronizationProcessor.processAfterCommit(ExpressionEvaluatingTransactionSynchronizationProcessor.java:125) ~[spring-integration-core-5.5.8.jar:5.5.8]
    at org.springframework.integration.transaction.DefaultTransactionSynchronizationFactory$DefaultTransactionalResourceSynchronization.processResourceAfterCommit(DefaultTransactionSynchronizationFactory.java:79) ~[spring-integration-core-5.5.8.jar:5.5.8]
    at org.springframework.integration.transaction.DefaultTransactionSynchronizationFactory$DefaultTransactionalResourceSynchronization.processResourceAfterCommit(DefaultTransactionSynchronizationFactory.java:53) ~[spring-integration-core-5.5.8.jar:5.5.8]
    at org.springframework.transaction.support.ResourceHolderSynchronization.afterCommit(ResourceHolderSynchronization.java:87) ~[spring-tx-5.3.15.jar:5.3.15]
    at org.springframework.transaction.support.TransactionSynchronizationUtils.invokeAfterCommit(TransactionSynchronizationUtils.java:135) ~[spring-tx-5.3.15.jar:5.3.15]
    at org.springframework.transaction.support.TransactionSynchronizationUtils.triggerAfterCommit(TransactionSynchronizationUtils.java:123) ~[spring-tx-5.3.15.jar:5.3.15]
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.triggerAfterCommit(AbstractPlatformTransactionManager.java:936) ~[spring-tx-5.3.15.jar:5.3.15]
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:782) ~[spring-tx-5.3.15.jar:5.3.15]
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:711) ~[spring-tx-5.3.15.jar:5.3.15]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:654) ~[spring-tx-5.3.15.jar:5.3.15]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:407) ~[spring-tx-5.3.15.jar:5.3.15]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119) ~[spring-tx-5.3.15.jar:5.3.15]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.15.jar:5.3.15]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215) ~[spring-aop-5.3.15.jar:5.3.15]
    at jdk.proxy2/jdk.proxy2.$Proxy101.call(Unknown Source) ~[na:na]
    at org.springframework.integration.endpoint.AbstractPollingEndpoint.pollForMessage(AbstractPollingEndpoint.java:413) ~[spring-integration-core-5.5.8.jar:5.5.8]
    at org.springframework.integration.endpoint.AbstractPollingEndpoint.lambda$createPoller$4(AbstractPollingEndpoint.java:348) ~[spring-integration-core-5.5.8.jar:5.5.8]
    at org.springframework.integration.util.ErrorHandlingTaskExecutor.lambda$execute$0(ErrorHandlingTaskExecutor.java:57) ~[spring-integration-core-5.5.8.jar:5.5.8]
    at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50) ~[spring-core-5.3.15.jar:5.3.15]
    at org.springframework.integration.util.ErrorHandlingTaskExecutor.execute(ErrorHandlingTaskExecutor.java:55) ~[spring-integration-core-5.5.8.jar:5.5.8]
    at org.springframework.integration.endpoint.AbstractPollingEndpoint.lambda$createPoller$5(AbstractPollingEndpoint.java:341) ~[spring-integration-core-5.5.8.jar:5.5.8]
    at org.springframework.cloud.sleuth.instrument.async.TraceRunnable.run(TraceRunnable.java:64) ~[spring-cloud-sleuth-instrumentation-3.1.0.jar:3.1.0]
    at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) ~[spring-context-5.3.15.jar:5.3.15]
    at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:95) ~[spring-context-5.3.15.jar:5.3.15]
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:539) ~[na:na]
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na]
    at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:304) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635) ~[na:na]
    at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na]

If I understood things correctly, the IntegrationFlowContext is responsible for the creation of the integration-beans (and thus the setting of the beanFactory). But then why do I get this error message?


问:
Receive numbers till the input is number that % 7 is without remainder
i got the next exercise in Javascript:

Receive whole numbers from the user, until he enters a number that % 7 with no remainder.
For each number received, state whether it is positive, negative or 0.
when inserting a number % by 7 with no remainder, end the program.

here is my code:

```<code>let num = +prompt("give us a number")
while (num % 7 != 0) {

    if (num > 0){
        document.write("positive ")
        num = +prompt("give us a number" )
    } else if (num < 0) {
        document.write("negative ")
        num = +prompt("give us a number" )
    } else if (num === 0) {
        document.write("zero ")
        num = +prompt("give us a number" )
    }
</code>```

The thing is, when the user enter 0 ,obviously i wont get output "zero", cause 0 % 7 is 0 remainder, so it dosent even get into the loop..so how can i output "zero" when the user enter 0?

答:
it turned out, this this the simplest answer:</p>
```<code>let num = +prompt("give us a number")
while (**num == 0| num % 7 != 0**) {
    if (num > 0){
        document.write("positive ")
        num = +prompt("give us a number" )
    } else if (num < 0) {
        document.write("negative ")
        num = +prompt("give us a number" )
    } else if (num === 0) {
        document.write("zero ")
        num = +prompt("give us a number" )
    }
}
</code>```

Body:
i got the next exercise in Javascript:

Receive whole numbers from the user, until he enters a number that % 7 with no remainder.
For each number received, state whether it is positive, negative or 0.
when inserting a number % by 7 with no remainder, end the program.

here is my code:

let num = +prompt("give us a number")
while (num % 7 != 0) {

    if (num > 0){
        document.write("positive ")
        num = +prompt("give us a number" )
    } else if (num < 0) {
        document.write("negative ")
        num = +prompt("give us a number" )
    } else if (num === 0) {
        document.write("zero ")
        num = +prompt("give us a number" )
    }

The thing is, when the user enter 0 ,obviously i wont get output "zero", cause 0 % 7 is 0 remainder, so it dosent even get into the loop..so how can i output "zero" when the user enter 0?

Body:
it turned out, this this the simplest answer:

let num = +prompt("give us a number")
while (**num == 0| num % 7 != 0**) {
    if (num > 0){
        document.write("positive ")
        num = +prompt("give us a number" )
    } else if (num < 0) {
        document.write("negative ")
        num = +prompt("give us a number" )
    } else if (num === 0) {
        document.write("zero ")
        num = +prompt("give us a number" )
    }
}


问:
Access all files on android
I am trying to make a file manager type application and I want to access all files. I know it will need MANAGE_EXTERNAL_STORAGE permission but I am not able to figure out which api should I use.</p>

答:
I am trying to make a file manager type application and I want to access all files.

I'll recommend you to start from here : Manage all files on a storage device (keep in mind you cannot write internal storage on a non-rooted device).

I am not able to figure out which api should I use.

MediaStore might suit your needs (even if your question is a bit generic) , so give it a reading to Access media files from shared storage.

Title: Access all files on android


问:
How to iterate through all keys of json node
I'm trying to scrap the key values from this website API and it seems the json format it's not an array.
I'm working with console .Net core 6.0 using System.Text.Json.Nodes

The code I'm using is :

```<code>    Dim streamData As Stream = Nothing
    Using http As HttpClient = New HttpClient
        Dim url As String = "https://api.hotbit.io/api/v1/market.status24h"

        Dim t As Task(Of Stream) = http.GetStreamAsync(url)
        streamData = t.Result
    End Using

    Dim jsonResponse As JsonNode = JsonNode.Parse(streamData)
    Dim jsonData As JsonNode = jsonResponse("result")

    Dim c As String = String.Empty

    For Each jsonCurrency As JsonNode In jsonData.AsObject
        c += jsonCurrency("last").ToString + " "
    Next
</code>```

but I get the error:

Cannot convert type 'KeyValuePair(Of String, JsonNode)' in JsonNode

What Am I doing wrong?
Thanks

答:
Create a class to represent your JSON, like this:

Public Class MarketStatus
    Public Property IsChange As Boolean
    Public Property period As Integer
    Public Property open As String
    Public Property last As String
    Public Property high As String
    Public Property low As String
    Public Property volume As String
    Public Property deal As String
    Public Property close As String
    Public Property base_volume As String
    Public Property quote_volume As String
End Class

Public Class Payload
    Public Property _error As Object
    Public Property result As Result
    Public Property id As Integer
End Class

Public Class Result

    <JsonPropertyName("0xBTCBTC")>
    Public Property _0xBTCBTC As MarketStatus

    <JsonPropertyName("0xBTCETH")>
    Public Property _0xBTCETH As MarketStatus

    <JsonPropertyName("0xCASHUSDT")>
    Public Property _0xCASHUSDT As MarketStatus

    <JsonPropertyName("1INCH1D3LUSDT")>
    Public Property _1INCH1D3LUSDT As MarketStatus

    ' etc...
End Class
```
<p>Now you can deserialize the entire payload by using JsonSerializer.Deserialize or JsonSerializer.DeserializeAsync:</p>
<pre class="lang-vb prettyprint-override"><code>Dim payloadObject = Await JsonSerializer.DeserializeAsync(Of Payload)(streamData)
</code>```

Update

Per our conversation in the comments of this answer, you want to get the last value of each MarketStatus without having to type each one manually. What you can do is:

Use reflection to get every property of the Result class

Loop over the collection

Use PropertyInfo.GetValue to get the value of the deserialized object

Here is an example using the same variable names as above:

For Each propertyInformation In GetType(Result).GetProperties()
    Dim status = DirectCast(propertyInformation.GetValue(payloadObject.result), MarketStatus)
    Console.WriteLine("{0}.last = {1}", propertyInformation.Name, status.last)
Next
```

Fiddle: https://dotnetfiddle.net/USaAgc

Body:
I'm trying to scrap the key values from this website API and it seems the json format it's not an array.
I'm working with console .Net core 6.0 using System.Text.Json.Nodes

The code I'm using is :

    Dim streamData As Stream = Nothing
    Using http As HttpClient = New HttpClient
        Dim url As String = "https://api.hotbit.io/api/v1/market.status24h"

        Dim t As Task(Of Stream) = http.GetStreamAsync(url)
        streamData = t.Result
    End Using

    Dim jsonResponse As JsonNode = JsonNode.Parse(streamData)
    Dim jsonData As JsonNode = jsonResponse("result")

    Dim c As String = String.Empty

    For Each jsonCurrency As JsonNode In jsonData.AsObject
        c += jsonCurrency("last").ToString + " "
    Next

but I get the error:

Cannot convert type 'KeyValuePair(Of String, JsonNode)' in JsonNode

What Am I doing wrong?
Thanks

Body:
Create a class to represent your JSON, like this:

Public Class MarketStatus
    Public Property IsChange As Boolean
    Public Property period As Integer
    Public Property open As String
    Public Property last As String
    Public Property high As String
    Public Property low As String
    Public Property volume As String
    Public Property deal As String
    Public Property close As String
    Public Property base_volume As String
    Public Property quote_volume As String
End Class

Public Class Payload
    Public Property _error As Object
    Public Property result As Result
    Public Property id As Integer
End Class

Public Class Result

    <JsonPropertyName("0xBTCBTC")>
    Public Property _0xBTCBTC As MarketStatus

    <JsonPropertyName("0xBTCETH")>
    Public Property _0xBTCETH As MarketStatus

    <JsonPropertyName("0xCASHUSDT")>
    Public Property _0xCASHUSDT As MarketStatus

    <JsonPropertyName("1INCH1D3LUSDT")>
    Public Property _1INCH1D3LUSDT As MarketStatus

    ' etc...
End Class

Now you can deserialize the entire payload by using JsonSerializer.Deserialize or JsonSerializer.DeserializeAsync:

Dim payloadObject = Await JsonSerializer.DeserializeAsync(Of Payload)(streamData)

Update

Per our conversation in the comments of this answer, you want to get the last value of each MarketStatus without having to type each one manually. What you can do is:

Use reflection to get every property of the Result class

Loop over the collection

Use PropertyInfo.GetValue to get the value of the deserialized object

Here is an example using the same variable names as above:

For Each propertyInformation In GetType(Result).GetProperties()
    Dim status = DirectCast(propertyInformation.GetValue(payloadObject.result), MarketStatus)
    Console.WriteLine("{0}.last = {1}", propertyInformation.Name, status.last)
Next

Fiddle: https://dotnetfiddle.net/USaAgc


答:
First, I would separate the test list data into different groups based on their test number, then I would product all the different lists of each test number. Both will be achieved using groupby and product function from itertools

from itertools import groupby, product

def get_test_number(test_string):
  return test_string[0:2]

my_list = ["t1v1", "t1v2", "t2v1", "t2v2", "t2v3"]
groupby_result = groupby(my_list, get_test_number)
separated_tests = [list(v) for _, v in groupby_result]
products = product(*separated_tests)
strings_of_products = list(map("_".join, products))
print(strings_of_products)
```

Title: Making combinations


问:
Exception in thread "main" java.lang.IllegalAccessError: class TestTarzan tried to access method 'void Tarzan.<init>(int, int)'
Absolute beginner in learning Java here. I'm trying to implement a class which accepts user input. Here is the code:

```<code>public class Tarzan {
    int total;
    int safe;

    Tarzan(int total, int safe) {
        this.total = total;
        this.safe = safe;
    }

    Tarzan() {
        total = 50;
        safe = 30;
    }

    int calculateResult() {
        int result = total - safe;
        return result;
    }
}
</code>```
```<code>import java.util.Scanner;

public class TestTarzan {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter total: ");
        int t = sc.nextInt();

        System.out.println("Enter safe: ");
        int s = sc.nextInt();

        Tarzan ta = new Tarzan(t, s);
        int res = ta.calculateResult();
        System.out.println(res);
        sc.close();
    }
}
</code>```

Then when running java .\TestTarzan.java, I got this error:

```<code>Exception in thread "main" java.lang.IllegalAccessError: class TestTarzan tried to access method 'void Tarzan.<init>(int, int)' (TestTarzan is in unnamed module of loader com.sun.tools.javac.launcher.Main$MemoryClassLoader @38c6f217; Tarzan is in unnamed module of loader 'app')
        at TestTarzan.main(TestTarzan.java:13)
</code>```

Any idea why?

答:
You need to change the visibility of the constructor and methods to public, or to another visible access modifier

```<code>    public Tarzan(int total, int safe) {
        this.total = total;
        this.safe = safe;
    }

    public Tarzan() {
        total = 50;
        safe = 30;
    }
    public int calculateResult() {
        int result = total - safe;
        return result;
    }

</code>```

https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

Body:
Absolute beginner in learning Java here. I'm trying to implement a class which accepts user input. Here is the code:

public class Tarzan {
    int total;
    int safe;

    Tarzan(int total, int safe) {
        this.total = total;
        this.safe = safe;
    }

    Tarzan() {
        total = 50;
        safe = 30;
    }

    int calculateResult() {
        int result = total - safe;
        return result;
    }
}

import java.util.Scanner;

public class TestTarzan {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter total: ");
        int t = sc.nextInt();

        System.out.println("Enter safe: ");
        int s = sc.nextInt();

        Tarzan ta = new Tarzan(t, s);
        int res = ta.calculateResult();
        System.out.println(res);
        sc.close();
    }
}

Then when running java .\TestTarzan.java, I got this error:

Exception in thread "main" java.lang.IllegalAccessError: class TestTarzan tried to access method 'void Tarzan.<init>(int, int)' (TestTarzan is in unnamed module of loader com.sun.tools.javac.launcher.Main$MemoryClassLoader @38c6f217; Tarzan is in unnamed module of loader 'app')
        at TestTarzan.main(TestTarzan.java:13)

Any idea why?

Body:
You need to change the visibility of the constructor and methods to public, or to another visible access modifier

    public Tarzan(int total, int safe) {
        this.total = total;
        this.safe = safe;
    }

    public Tarzan() {
        total = 50;
        safe = 30;
    }
    public int calculateResult() {
        int result = total - safe;
        return result;
    }

https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html


问:
Synchronizing a countdown timer through Firestore
Creating an app in Javascript in which I'm creating a timer that updates at every second and so, I want to store that timers time in firebase firestore at every  update in timer so I could retrieve it with Onsnapshot on another page for displaying what would be an efficient way to do this because I don't think updating DOC every second will be a good approach</p>

答:
Synchronizing each tick across the database is indeed not very efficient. But time has the nice trait that it passes (for the purpose of a use-case such as this) at the same rate on all clients. So what you'll want to do instead is store the start time and the interval of the timer in the database, and then have each client run its own local countdown based on that.

I wrote an example of this using the Firebase Realtime Database, so I recommend checking that out as a starting point: How to implement a distributed countdown timer in Firebase


问:
I am trying to filter products in assending and descending order based on product price in vue js using vuex. But not sure how to do
I have been following youtube tutorials for learning Vue js.
so I want to add functionality to this project for filtering the products based upon price.

here is my  code

store/index.js

```<code>import { createStore } from 'vuex'

function updateLocalStorage(cart) {
    localStorage.setItem('cart', JSON.stringify(cart))
}

export default createStore({
    state: {
        cart: [],
    },
    getters: {
        productQuantity: state => product => {
            const item = state.cart.find(i => i.id === product.id)
            if (item) {
                return item.quantity;
            } else {
                return null;
            }
        },
        cartItems: state => {
            return state.cart
        },
        cartToatal: state => {
            return state.cart.reduce((a, b) => a + (b.val * b.quantity), 0)
        }
    },
    mutations: {
        addItemInCart(state, product) {
            let item = state.cart.find(i => i.id === product.id)

            if (item) {
                item.quantity++;
            } else {
                state.cart.push({...product, quantity: 1 });
            }

            updateLocalStorage(state.cart);
        },
        removeItemFromCart(state, product) {
            let item = state.cart.find(i => i.id === product.id)
            if (item) {
                if (item.quantity > 1) {
                    item.quantity--
                } else {
                    state.cart = state.cart.filter(i => i.id != product.id)
                }
            }

            updateLocalStorage(state.cart);
        },
        updateCartFromLocalStorage(state) {
            const cart = localStorage.getItem('cart')
            if (cart) {
                state.cart = JSON.parse(cart)
            }
        }
    },
    actions: {},
    modules: {}
})
</code>```

here is what my look like in file data/items.js

```<code>const items = [{
        id: 1,
        name: "One Tribe Black Edition",
        img: "https://enftymart.themenio.com/img/nft-lg.8f26d1a6.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 2,
        name: "One Tribe Black New",
        img: "https://miro.medium.com/max/2000/1*AJrLFnuCAD8dE1p1Bg0dbg.jpeg",
        val: "15.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 3,
        name: "One Tribe Black Edition",
        img: "https://creativereview.imgix.net/content/uploads/2021/09/F4E079D612B9653BEFC4D8D2F39781E39A3025C693B177A61D6C73A5156248EA.jpg?auto=compress,format&q=60&w=1200&h=849",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 4,
        name: "One Tribe Black Edition",
        img: "https://coffeebros.com/wp-content/uploads/2021/10/astronaut-background.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 5,
        name: "One Tribe Black Edition",
        img: "https://cloudfront-us-east-1.images.arcpublishing.com/coindesk/5NOWWNNEBRER7BXFZKCYRCA7NA.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 6,
        name: "One Tribe Black Edition",
        img: "https://static01.nyt.com/images/2021/08/15/fashion/TEEN-NFTS--fewocious/TEEN-NFTS--fewocious-videoSixteenByNineJumbo1600.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 7,
        name: "One Tribe Black Edition",
        img: "https://miro.medium.com/max/980/1*3iesg_sr8kC6NYN2iiFHRQ.png",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 8,
        name: "One Tribe Black Edition",
        img: "https://static01.nyt.com/images/2021/08/15/fashion/TEEN-NFTS--fewocious/TEEN-NFTS--fewocious-videoSixteenByNineJumbo1600.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 9,
        name: "One Tribe Black Edition",
        img: "https://www.digitalmusicnews.com/wp-content/uploads/2021/11/are-nfts-a-scam-feat.png",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 10,
        name: "One Tribe Black Edition",
        img: "https://miro.medium.com/max/1082/1*ZZdfsIVNuvbWB15csehQTg.jpeg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 11,
        name: "One Tribe Black Edition",
        img: "https://www.hollywoodreporter.com/wp-content/uploads/2021/10/Mutant-Demon-Ape-Credit-0xb1-copy-H-2021.jpg?w=681&h=383&crop=1",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 12,
        name: "One Tribe Black Edition",
        img: "https://wp-assets.futurism.com/2021/11/person-furious-right-click-saved-precious-nft.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
]

export default items
</code>```

here is the Vue page where I am trying to filter products I have created to buttons and to methods for descending and ascending order.

```<code><template>
  <div class="home">
    <span class="big-text">NFT</span>
    <div class="nx-container">
      <h1 class="py-45">Get NFT</h1>
      <button class="sort-as" @click="sortUp()">sort up</button>
      <button class="sort-as" @click="sortDown()">sort down</button>
      <div class="flex-it pad-130">
        <product-details
          :product="product"
          :active="active.product_detail"
          v-on:closeDetails="closeDetails()"
        ></product-details>
        <product-summary-container
          v-for="product in items"
          :key="product.id"
          :product="product"
          v-on:explore="viewProduct($event)"
        ></product-summary-container>
      </div>
    </div>
  </div>
</template>

<script>
import ProductSummaryContainer from "../components/products/ProductSummaryContainer.vue";
import ProductDetails from "../components/products/ProductDetails.vue";

import items from "../data/items";

export default {
  name: "Home",
  components: { ProductSummaryContainer, ProductDetails },
  data() {
    return {
      items: items,
      product: null,
      active: {
        product_detail: false,
      },
    };
  },
  methods: {
    viewProduct(product) {
      this.product = product;
      this.active.product_detail = true;
      console.log(product);
    },
    closeDetails() {
      this.active.product_detail = false;
    },
    sortUp($store) { //what i tried
      console.log(this.$store.items.val.sort((a, b) => a - b));
      return $store.items.val.sort((a, b) => a - b);
    },
    sortDown() {},//what i tried
  },
};
</script>

<style>
* {
  margin: 0;
  padding: 0;
  text-align: initial;
}
.nx-container {
  max-width: 1200px;
  overflow-x: hidden;
  overflow-y: auto;
  margin: 0 auto;
}
.flex-it {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}
.pad-130 {
  padding: 0px 15px 130px;
}
.big-text {
  font-family: "Poppins";
  font-size: 16em;
  text-transform: uppercase;
  font-weight: 800;
  position: absolute;
  top: 0;
  right: 0;
  z-index: -6;
  -webkit-text-fill-color: transparent;
  -webkit-text-stroke-width: 0.3px;
}
#app {
  position: relative;
}
</style>
</code>```

what changes need to be done?
Thank you in advance.

答:
There is a lot of missing pieces to your code like how you're iterating over the list of items in the DOM so I can't give a full answer but I think you're simply referencing this.items wrong when you're attempting to sort the list of items in sortUp. you may want your code to be something similar to the following:

```<code>    sortUp() {
      return items.sort((a, b) => parseFloat(a.val) - parseFloat(b.val));
    },
</code>```

Body:
I have been following youtube tutorials for learning Vue js.
so I want to add functionality to this project for filtering the products based upon price.

here is my  code

store/index.js

import { createStore } from 'vuex'

function updateLocalStorage(cart) {
    localStorage.setItem('cart', JSON.stringify(cart))
}

export default createStore({
    state: {
        cart: [],
    },
    getters: {
        productQuantity: state => product => {
            const item = state.cart.find(i => i.id === product.id)
            if (item) {
                return item.quantity;
            } else {
                return null;
            }
        },
        cartItems: state => {
            return state.cart
        },
        cartToatal: state => {
            return state.cart.reduce((a, b) => a + (b.val * b.quantity), 0)
        }
    },
    mutations: {
        addItemInCart(state, product) {
            let item = state.cart.find(i => i.id === product.id)

            if (item) {
                item.quantity++;
            } else {
                state.cart.push({...product, quantity: 1 });
            }

            updateLocalStorage(state.cart);
        },
        removeItemFromCart(state, product) {
            let item = state.cart.find(i => i.id === product.id)
            if (item) {
                if (item.quantity > 1) {
                    item.quantity--
                } else {
                    state.cart = state.cart.filter(i => i.id != product.id)
                }
            }

            updateLocalStorage(state.cart);
        },
        updateCartFromLocalStorage(state) {
            const cart = localStorage.getItem('cart')
            if (cart) {
                state.cart = JSON.parse(cart)
            }
        }
    },
    actions: {},
    modules: {}
})

here is what my look like in file data/items.js

const items = [{
        id: 1,
        name: "One Tribe Black Edition",
        img: "https://enftymart.themenio.com/img/nft-lg.8f26d1a6.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 2,
        name: "One Tribe Black New",
        img: "https://miro.medium.com/max/2000/1*AJrLFnuCAD8dE1p1Bg0dbg.jpeg",
        val: "15.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 3,
        name: "One Tribe Black Edition",
        img: "https://creativereview.imgix.net/content/uploads/2021/09/F4E079D612B9653BEFC4D8D2F39781E39A3025C693B177A61D6C73A5156248EA.jpg?auto=compress,format&q=60&w=1200&h=849",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 4,
        name: "One Tribe Black Edition",
        img: "https://coffeebros.com/wp-content/uploads/2021/10/astronaut-background.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 5,
        name: "One Tribe Black Edition",
        img: "https://cloudfront-us-east-1.images.arcpublishing.com/coindesk/5NOWWNNEBRER7BXFZKCYRCA7NA.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 6,
        name: "One Tribe Black Edition",
        img: "https://static01.nyt.com/images/2021/08/15/fashion/TEEN-NFTS--fewocious/TEEN-NFTS--fewocious-videoSixteenByNineJumbo1600.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 7,
        name: "One Tribe Black Edition",
        img: "https://miro.medium.com/max/980/1*3iesg_sr8kC6NYN2iiFHRQ.png",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 8,
        name: "One Tribe Black Edition",
        img: "https://static01.nyt.com/images/2021/08/15/fashion/TEEN-NFTS--fewocious/TEEN-NFTS--fewocious-videoSixteenByNineJumbo1600.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 9,
        name: "One Tribe Black Edition",
        img: "https://www.digitalmusicnews.com/wp-content/uploads/2021/11/are-nfts-a-scam-feat.png",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 10,
        name: "One Tribe Black Edition",
        img: "https://miro.medium.com/max/1082/1*ZZdfsIVNuvbWB15csehQTg.jpeg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 11,
        name: "One Tribe Black Edition",
        img: "https://www.hollywoodreporter.com/wp-content/uploads/2021/10/Mutant-Demon-Ape-Credit-0xb1-copy-H-2021.jpg?w=681&h=383&crop=1",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 12,
        name: "One Tribe Black Edition",
        img: "https://wp-assets.futurism.com/2021/11/person-furious-right-click-saved-precious-nft.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
]

export default items

here is the Vue page where I am trying to filter products I have created to buttons and to methods for descending and ascending order.

<template>

    NFT

Get NFT

      <button class="sort-as" @click="sortUp()">sort up</button>
      <button class="sort-as" @click="sortDown()">sort down</button>

        <product-details
          :product="product"
          :active="active.product_detail"
          v-on:closeDetails="closeDetails()"
        ></product-details>
        <product-summary-container
          v-for="product in items"
          :key="product.id"
          :product="product"
          v-on:explore="viewProduct($event)"
        ></product-summary-container>

</template>

what changes need to be done?
Thank you in advance.

Body:
There is a lot of missing pieces to your code like how you're iterating over the list of items in the DOM so I can't give a full answer but I think you're simply referencing this.items wrong when you're attempting to sort the list of items in sortUp. you may want your code to be something similar to the following:

    sortUp() {
      return items.sort((a, b) => parseFloat(a.val) - parseFloat(b.val));
    },


问:
How to save a list locally to a database with shared preferences in flutter?
How can I  save a list locally to a database with shared preferences in flutter .
for example :- I have list List notification = []; How can I save this list locally with shared preferences?</p>

答:
```<code>const  _notificationListKey='notificationList';
Future<void> notificationInLocalStorage( List notificationList ) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await Future.wait([
  prefs.setString(_notificationListKey,json.encode( notificationList)),
]);
}
</code>```


问:
discord js dont detect messages
so i made this code
and i don't know why my bot don't
detect any message?</p>
```<code>const { Client, Intents, Channel } = require('discord.js');
const bot = new Client( {intents: [Intents.FLAGS.GUILDS]});
const { token } = require("./config.json");
bot.once("ready",() => {
  console.log("połączony1");
  bot.user.setActivity("hej",{type: "WATCHING"})
})
bot.on('message', async msg =>  {
  console.log(msg.content);
});

bot.login(token);
</code>```

答:
Please try to add Intents.FLAGS.GUILD_MESSAGES to your Intents. This will make bot trigger on any messages in guilds (discord servers).

Also, if you're using v13 of Discord.js, keep in mind that 'message' event has been deprecated in favour of 'messageCreate' (source: https://discordjs.guide/additional-info/changes-in-v13.html#naming-conventions)

Title: discord js dont detect messages

Body:
so i made this code
and i don't know why my bot don't
detect any message?

const { Client, Intents, Channel } = require('discord.js');
const bot = new Client( {intents: [Intents.FLAGS.GUILDS]});
const { token } = require("./config.json");
bot.once("ready",() => {
  console.log("połączony1");
  bot.user.setActivity("hej",{type: "WATCHING"})
})
bot.on('message', async msg =>  {
  console.log(msg.content);
});

bot.login(token);